mybatis-generator官方文档
1、导入jar包
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.6</version>
</dependency>
2、编写配置文件mbg.xml(resources/)
targetRuntime属性说明:
MyBatis3Simple:基本的增删改查
MyBatis3:带条件查询的增删改查【QBC(query By Criteria)】
<!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="simple" targetRuntime="MyBatis3simple">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test_mybatis?serverTimezone=UTC"
userId="root"
password="123456">
<!-- mysql8要加下面这一行-->
<property name="nullCataLogMeansCurrent" value="true"/>
</jdbcConnection>
<!-- 设置javabean的生成策略-->
<javaModelGenerator targetPackage="com.atguigu.mybatis.pojo" targetProject="src/main/java"/>
<!-- 设置sql映射文件的生成策略-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!-- 设置Mapper接口的生成策略-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mybatis.mapper" targetProject="src/main/java"/>
<!-- 逆向分析的表-->
<table tableName="tbl_employee" domainObjectName="Employee"/>
<table tableName="tbl_dept" domainObjectName="Department"/>
</context>
</generatorConfiguration>
3、测试生成代码
@Test
public void test01(){
try {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("src/main/resources/mbg.xml");
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 (IOException e) {
e.printStackTrace();
} catch (XMLParserException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
4、QBC风格的测试
@Test
public void test028(){
SqlSessionFactory sqlSessionFactory = null;
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = employeeMapper.selectByPrimaryKey(1);
System.out.println(employee);
EmployeeExample ee=new EmployeeExample();
EmployeeExample.Criteria criteria=ee.createCriteria();
List<Integer> ids=new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(6);
criteria.andIdIn(ids);
criteria.andLastNameLike("人人");
List<Employee> employees = employeeMapper.selectByExample(ee);
for (Employee employee1 : employees) {
System.out.println(employee1);
}
}