1, MyBatisGenerator installation
When using mybatis, we need to repeatedly create pojo classes, mapper files and dao classes, and configure the dependencies between them. It is troublesome and has done a lot of repeated work. Mybatis officials have also found this problem, so we have provided mybatis generator tool to help us automatically create pojo classes Mapper files and dao classes will help us configure their dependencies.
However, we need to manually write SQL tables and stored procedures.
1. Official website address:
2. Join dependency
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency>
3. Create configuration file: MBG xml
Create the resources directory under the src/test directory
Create MGB. In the resources directory xml
The directory structure is as follows:
mbg.xml configuration:
<?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="DB2Tables" targetRuntime="MyBatis3"> <!-- Configure built-in or custom Plugin --> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- Database link URL,User name and password --> <jdbcConnection driverClass="org.h2.Driver" connectionURL="jdbc:h2:./src/main/resources/db/test" userId="sa" password="123"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- Package name and location of the build model --> <javaModelGenerator targetPackage="org.example.entity" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- Generated Mapper Interface and location --> <sqlMapGenerator targetPackage="org.example.mapper" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- generate Mapper Profile and location --> <javaClientGenerator type="XMLMAPPER" targetPackage="org.example.mapper" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- Table to generate tableName Is the name of a table or view in the database domainObjectName Is the entity class name--> <table tableName="student" domainObjectName="student"/> <table tableName="teacher" domainObjectName="teacher"/> </context> </generatorConfiguration>
Key points to be configured:
- Data source: < JDBC connection >
<jdbcConnection driverClass="org.h2.Driver" connectionURL="jdbc:h2:./src/main/resources/db/test" userId="sa" password="123"> </jdbcConnection>
- Entity, Mapper interface, Mapper configured < targetpackage >
<!-- Package name and location of the build model --> <javaModelGenerator targetPackage="org.example.entity" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- Generated Mapper Interface and location --> <sqlMapGenerator targetPackage="org.example.mapper" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- generate Mapper Profile and location --> <javaClientGenerator type="XMLMAPPER" targetPackage="org.example.mapper" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator>
- Table name to be generated < table / >
To generate all tables, you can write<!-- Table to generate tableName Is the name of a table or view in the database domainObjectName Is the entity class name--> <table tableName="student" domainObjectName="student"/> <table tableName="teacher" domainObjectName="teacher"/>
<table tableName="%"/>
4. Perform reverse engineering
Create a test class GeneratorTest
/** * @description: mybatis Code generator * */ public class GeneratorTest { @Test public void generate(){ try { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File(GeneratorTest.class.getResource("/mbg.xml").getFile()); ConfigurationParser cp = new ConfigurationParser(warnings); Configuration config = cp.parseConfiguration(configFile); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } catch (Exception e) { e.printStackTrace(); } } }
2, MyBatisGenerator common method operation
Create test class StudentTest
/** * @description: Student testing */ public class StudentTest { private SqlSession openSession; private StudentMapper mapper; @Before public void testBefore(){ try { //Create SQLSession factory SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")); //Open session openSession = factory.openSession(true); //Get mapper mapper = openSession.getMapper(StudentMapper.class); } catch (IOException e) { e.printStackTrace(); } } @After public void testAfter(){ openSession.close(); } }
1. Query by id
@Test public void testFindStudentById(){ Student student = mapper.selectByPrimaryKey(1); System.out.println(student); }
2. Condition query
For example: query id=1, name = "Tang Seng"
To use a conditional query, you must use the Criteria object, which can splice many conditions, starting with andXXX.
@Test public void testSelectByExample() { //Query by criteria StudentExample example = new StudentExample(); Criteria criteria = example.createCriteria(); criteria.andIdEqualTo(1); criteria.andNameEqualTo("Tang Monk"); List<Student> list = mapper.selectByExample(example); System.out.println(list); }
3. Fuzzy query
For example, the query name contains "Tang".
It is also a conditional query, using the andNameLike method of the Criteria object
@Test public void testSelectByExample2() { //Query by criteria StudentExample example = new StudentExample(); Criteria criteria = example.createCriteria(); criteria.andNameLike("%Tang%"); List<Student> list = mapper.selectByExample(example); System.out.println(list); }
4. Sort
For example: all students in reverse order
@Test public void testOrderByClause() { StudentExample example = new StudentExample(); example.setOrderByClause("id DESC"); List<Student> list = mapper.selectByExample(example); System.out.println(list); }
5. Paging query
MyBatis Generator can extend its functions through plug-in mechanism. RowBoundsPlugin is a paging plug-in in MyBatis Generator. You can create generatorconfig. In the MyBatis Generator configuration file Add this plug-in to XML
<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"/>
Execute reverse engineering GeneratorTest again to generate code. At this time, you will find that a new method will be added to the generated Mapper:
selectByExampleWithRowbounds(XxxExampleexample,RowBoundsrowBounds) can call this method in code to achieve paging:
Note: it is recommended to manually delete the generated files before generating.
@Test public void testSelectByExampleWithRowbounds() { int pagerNow = 2; int pagerSize = 3; pagerNow = (pagerNow-1)*pagerSize; StudentExample example = new StudentExample(); RowBounds rowBounds = new RowBounds(pagerNow, pagerSize); List<Student> list = mapper.selectByExampleWithRowbounds(example, rowBounds); System.out.println(list); }
6. "or" splicing between multiple conditions
For example: query (the name contains "Tang" and the id is between 1 and 10), or (the teacher number is not 2).
@Test public void testMoreExUseOr() { StudentExample example = new StudentExample(); //First create a Criteria object to set the conditions in the first bracket Criteria criteria1 = example.createCriteria(); criteria1.andNameLike("%Tang%").andIdBetween(1, 10); //Create a Criteria object to set the conditions in the second bracket Criteria criteria2 = example.createCriteria(); criteria2.andTidNotEqualTo(2); //Merge two example s example.or(criteria2); List<Student> list = mapper.selectByExample(example); System.out.println(list); }
7. Add
@Test public void testInsert() { Student student = new Student(); student.setName("Chang'e"); student.setAge(1000); student.setEmail("ce@163.com"); mapper.insert(student); }
8. Modification
- Non null judgment
@Test public void testUpdateByPrimaryKey() { Student student = new Student(); student.setId(28); student.setName("Chang'e"); student.setAge(10000); student.setEmail("ce@163.com"); mapper.updateByPrimaryKey(student); }
- Non null judgment
@Test public void testUpdateByPrimaryKeySelective() { Student student = new Student(); student.setId(28); student.setName("Chang'e-2"); mapper.updateByPrimaryKeySelective(student); }
9. Delete
@Test public void testDeleteByPrimaryKey() { mapper.deleteByPrimaryKey(28); }
3, Conclusion
The study of Mybatis is over here. The content of these notes is relatively simple and can only be regarded as an introductory tutorial. If there are any mistakes, please correct them in the comment area.
After getting started with Mybatis, you can learn about Mybatis brothers MybatisPlus . MybatisPlus is simpler and more efficient than Mybatis.