Hello, I'm the elder brother of Chinese menong green tea.
Welcome to my personal WeChat official account: 8 Kangyuan road!
Mybatis-demo
1. Explanation of professional terms
1.1 Dao
Dao layer is called data access layer and persistence layer, and its full name is Data access object. It is a kind of bottom-level and basic operation. It is specific to the addition, deletion, modification and query of a table, that is, a Dao must correspond to a table in the database one by one. It encapsulates the basic operations of addition, deletion, modification and query, and queries data completely according to the requirements of the Domain, It is recommended that Dao only perform atomic operations, add, delete, modify and check.
1.2 Domain
The Domain layer considers business logic, such as filtering conditions, release or return, and data processing, to prepare for calling the Dao layer. A Domain can call one or a group of related Dao layers.
1.3 Service
The Service layer is called the Service layer, which is called the Service layer. The Service layer calls one or a group of Domain layers, which mainly shows the interfaces that need to be opened. Not all interfaces of the Domain layer need to be reflected in the Service layer, and only a few interfaces may be opened in the Service layer. In addition, the main interface needs to expand the accepted parameters as much as possible, that is, it can accommodate the access (Object) of various types of parameters, and then it needs to be converted in the Service layer for use by the Domain layer.
1.4 Controler
The controller is responsible for forwarding the request, accepting the parameters from the page, transmitting them to the Service for processing, receiving the return value, and then transmitting them to the page.
1.5 business logic
The user sends a request - > the controller handles the transmitted parameters - > the domain receives the control data and turns (you can return or enter the service - > service to verify the correctness of the data or whether it meets the business requirements - > Dao deposit
2 Introduction to mybatis generator
MyBatis Generator (MBG) is the code generator for MyBatis, MyBatis and iBATIS. It will generate code for all versions of MyBatis and iBATIS versions after version 2.2.0. It will introspect database tables (or many tables) and generate artifacts that can be used to access tables. This reduces the initial hassle of setting up objects and configuration files to interact with database tables. MBG seeks simple CRUD Most database operations (create, retrieve, update, delete) have a significant impact. You still need to manually write SQL and object code for connection queries or stored procedures.
2.1 MyBatis Generator will generate
2.1. 1 Java POJO s matching the table structure
This may include:
- A class that matches the primary key of the table (if there is a primary key)
- A class that matches the non primary key field of the table (except BLOB field)
- Class containing the BLOB field of the table (if the table has a BLOB field)
- Classes used to enable dynamic selection, updating, and deletion
There are appropriate inheritance relationships between these classes. Note that the generator can be configured to generate different types of POJO hierarchies - for example, if you prefer, you can choose to generate a single domain object for each table.
2.1.2 MyBatis / iBATIS compatible SQL Map XML file
MBG generates SQL for simple CRUD functions on each table in the configuration. The generated SQL statements include:
- insert
- Update by primary key
- Update by example (using dynamic where clause)
- Delete by primary key
- Delete by example (using dynamic where clause)
- Select by primary key
- Select by example (using dynamic where clause)
- make oneself an example
According to the structure of the table, these statements have different variants (for example, if the table has no primary key, MBG will not generate updates through the primary key function).
2.1.3 properly use the Java client class of the above object
The generation of java client classes is optional. MBG will generate the following types of Java clients for MyBatis 3.x:
- Mapper interface for MyBatis 3.x mapper infrastructure
MBG will generate the following types of Java clients for iBATIS 2.x:
- Spring framework compliant DAO
- Only Daos that use iBATIS SQL mapping API. These Daos can generate two types: providing SqlMapClient through constructor or setter injection.
- DAO conforming to iBATIS DAO framework (an optional part of iBATIS. This framework is not recommended now. We recommend that you use Spring framework)
The MyBatis generator is designed to run well in an iterative development environment and can be included in a continuous build environment as an Ant task or Maven plug-in. Important considerations when iteratively running MBG include:
- If there is an existing file with the same name as the newly generated XML file, MBG will automatically merge the XML file. MBG will not overwrite any custom changes you have made to the XML file it generates. You can run it repeatedly without fear of losing custom changes to the XML. MBG will replace any XML elements generated in the previous run.
- MBG does not merge Java files. It can overwrite existing files or save newly generated files with different unique names. If you make changes to the generated Java files and run MBG iteratively, you must merge the changes manually. MBG can automatically merge Java files when running as an Eclipse plug-in.
3 MyBatis Generator download
3.1 source code address
https://github.com/mybatis/generator/releases
3.2 official documents
http://www.mybatis.org/generator/index.html
4 Mybatis Generator configuration and use
4.1 creation of database and data table
4.1.1 new database: mybatis demo
4.1.2 new data table ad
-- -- Table structure for table `ad` -- DROP TABLE IF EXISTS `ad`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ad` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(63) NOT NULL DEFAULT '' COMMENT 'Ad title', `link` varchar(255) NOT NULL DEFAULT '' COMMENT 'Link address of the advertised product page or activity page', `url` varchar(255) NOT NULL COMMENT 'Advertising pictures', `position` tinyint(3) DEFAULT '1' COMMENT 'Advertising position: 1 is the home page', `content` varchar(255) DEFAULT '' COMMENT 'Activity content', `start_time` datetime DEFAULT NULL COMMENT 'Advertising start time', `end_time` datetime DEFAULT NULL COMMENT 'Advertising end time', `enabled` tinyint(1) DEFAULT '0' COMMENT 'Start', `add_time` datetime DEFAULT NULL COMMENT 'Creation time', `update_time` datetime DEFAULT NULL COMMENT 'Update time', `deleted` tinyint(1) DEFAULT '0' COMMENT 'Logical deletion', PRIMARY KEY (`id`), KEY `enabled` (`enabled`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='Advertising list';
4.1.3 inserting data into data sheets
-- -- Dumping data for table `ad` -- LOCK TABLES `ad` WRITE; /*!40000 ALTER TABLE `ad` DISABLE KEYS */; INSERT INTO `ad` VALUES (1, 'Who is your dish', '', 'http://yanxuan.nosdn.127.net/65091eebc48899298171c2eb6696fe27.jpg', 1,' who is your dish ', NULL, NULL, 1, '2018-02-01 00:00:00', '2018-02-01 00:00:00', 0), (2, 'Activity Food Festival', '', 'http://yanxuan.nosdn.127.net/bff2e49136fcef1fd829f5036e07f116.jpg', 1,' active food festival ', NULL, NULL, 1, '2018-02-01 00:00:00', '2018-02-01 00:00:00', 0), (3, 'Activity mother's Day', '', 'http://Yanxuan. Nosdn. 127. Net / 8e50c65fda145e6dd1bf4fb7ee0fcc. JPG ', 1,' active mother's day 5', NULL, NULL, 1, '2018-02-01 00:00:00', '2018-02-01 00:00:00', 0); /*!40000 ALTER TABLE `ad` ENABLE KEYS */; UNLOCK TABLES;
4.2 new project mybatis demo
4.2.1 import plug-in in pom.xml
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <configurationFile> mybatis-generator/generatorConfig.xml </configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>com.itfsw</groupId> <artifactId>mybatis-generator-plugin</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> </dependencies> </plugin>
4.2.2 preparation of configuration files
Create a new folder mybatis generator under the root directory of the project, create a generatorConfig.xml file, and write in the file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="mysqlgenerator" targetRuntime="MyBatis3"> <property name="autoDelimitKeywords" value="true"/> <!--have access to``Include field names to avoid field names and sql Reserved word conflict error--> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <!-- Automatic generation toString method --> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/> <!-- Automatic generation equals Methods and hashcode method --> <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/> <!-- Unofficial plug-ins https://github.com/itfsw/mybatis-generator-plugin --> <!-- Query single data plug-in --> <plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/> <!-- Query result selective return plug-in --> <plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin"/> <!-- Example Criteria Enhanced plug-in --> <plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin"/> <!-- data Model Attribute correspondence Column Get plug-ins --> <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/> <!-- Logical delete plug-in --> <plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin"> <!-- The global logical deletion column and logical deletion value are configured here. Of course, in table The value configured in overrides the global configuration --> <!-- The type of a tombstone column can only be numeric, string, or Boolean --> <property name="logicalDeleteColumn" value="deleted"/> <!-- Logical deletion-Deleted value --> <property name="logicalDeleteValue" value="1"/> <!-- Logical deletion-Value not deleted --> <property name="logicalUnDeleteValue" value="0"/> </plugin> <commentGenerator> <property name="suppressDate" value="true"/> <!--<property name="suppressAllComments" value="true"/>--> </commentGenerator> <!--Database connection information--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/Mybatis-demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&verifyServerCertificate=false&useSSL=false" userId="root" password="root"/> <javaTypeResolver> <property name="useJSR310Types" value="true"/> </javaTypeResolver> <javaModelGenerator targetPackage="com.hyd.mybatisdemo.domain" targetProject="src/main/java"/> <sqlMapGenerator targetPackage="com.hyd.mybatisdemo.dao" targetProject="src/main/resources"/> <javaClientGenerator type="XMLMAPPER" targetPackage="com.hyd.mybatisdemo.dao" targetProject="src/main/java"/> <!--Table name--> <table tableName="ad"> <generatedKey column="id" sqlStatement="MySql" identity="true"/> </table> </context> </generatorConfiguration>
4.2.3 running plug-ins
Open Maven on the right side of the window, expand mybatis Demo - > plugin - > mybatis generator, and double-click mybatis generator: generate to see the console related information and the generated Dao, domain, com.hyd.mybatisdemo.dao
4.3 start use
4.3.1 create AdService.java
@Service public class AdService { @Resource private AdMapper adMapper; public List<Ad> queryIndex() { AdExample example = new AdExample(); example.or().andPositionEqualTo((byte) 1).andDeletedEqualTo(false).andEnabledEqualTo(true); return adMapper.selectByExample(example); } public List<Ad> querySelective(String name, String content, Integer page, Integer limit, String sort, String order) { AdExample example = new AdExample(); AdExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(name)) { criteria.andNameLike("%" + name + "%"); } if (!StringUtils.isEmpty(content)) { criteria.andContentLike("%" + content + "%"); } criteria.andDeletedEqualTo(false); if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) { example.setOrderByClause(sort + " " + order); } PageHelper.startPage(page, limit); return adMapper.selectByExample(example); } public int updateById(Ad ad) { ad.setUpdateTime(LocalDateTime.now()); return adMapper.updateByPrimaryKeySelective(ad); } public void deleteById(Integer id) { adMapper.logicalDeleteByPrimaryKey(id); } public void add(Ad ad) { ad.setAddTime(LocalDateTime.now()); ad.setUpdateTime(LocalDateTime.now()); adMapper.insertSelective(ad); } public Ad findById(Integer id) { return adMapper.selectByPrimaryKey(id); } }
4.3.2 create AdController.java
@RestController @RequestMapping public class AdController { @Autowired private AdService adService; @GetMapping("/getad") public Object getad() { ExecutorService executorService = Executors.newFixedThreadPool(10); Map<String, Object> data = new HashMap<>(); Callable<List> bannerListCallable = () -> adService.queryIndex(); FutureTask<List> bannerTask = new FutureTask<>(bannerListCallable); executorService.submit(bannerTask); try { data.put("banner", bannerTask.get()); } catch (Exception e) { e.printStackTrace(); } executorService.shutdown(); return ResponseUtil.ok(data); } }
4.3.3 test interface
http://localhost:8080/getad
5 project address
It's not easy to organize. Welcome Star and Fork, Thank you~~