mybatis03
mybatis 多表联查
- 背景产生:开发过程中单表查询 不能满足项目需求分析功能。对于复杂业务来说,关联的表有几张,甚至几十张 并且表与表之间的关系相当复杂。
- 目的:实现复杂业务功能,必须进行多表查询,在mybatis中提供了多表查询的结果 映射标签,可以实现一对一、一对多、多对一、多对多关系映射。
一、一对一
1、创建表
- 以 妻子表 和 丈夫表为例
drop database if exists db_418;
create database db_418;
use db_418;
create table wife(
wid int primary key auto_increment,
wname varchar(10) not null
);
create table husband(
hid int primary key auto_increment,
hname varchar(10) not null,
wid int,
foreign key(wid) references wife(wid)
);
2、业务需求
- 查询出所有丈夫信息 及其妻子信息
# SQL语句查询
select * from wife w,husband h where w.wid=h.wid;
3、项目准备
(1)项目结构
(2)maven项目,引入在pom.xml文件中引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.etime</groupId>
<artifactId>day0418</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
(3)配置数据源jdbc.properties属性文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_418
root=root
password=root
(4)配置 mapper映射文件信息
<?xml version="1.0" encoding="UTF-8"?>
<!--引入dtd约束-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置连接数据库的信息:动态的读-->
<properties resource="jdbc.properties"></properties>
<!--给实体类取别名-->
<typeAliases>
<package name="com.etime.pojo"/>
</typeAliases>
<!--配置mybatis的环境-->
<environments default="development">
<!--配置环境-->
<environment id="development">
<!--配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置链接数据库的信息:使用的是 数据源[连接池]-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${root}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--注册映射文件位置-->
<mappers>
<package name="com.etime.mapper"/>
</mappers>
</configuration>
(5)实体类:妻子类 和 丈夫类
- 妻子类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Wife {
private int wid;
private String wname;
}
- 丈夫类
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Husband {
private int hid;
private String hname;
private int wid;
private Wife wife;
}
(6)在 接口 HusbandMapper.java中定义方法
package com.etime.mapper;
import com.etime.pojo.Husband;
import java.util.List;
public interface HusbandMapper {
List<Husband> getAllHusband();
}
(7)在 映射文件 HusbandMapper.xml 中进行配置
<?xml version="1.0" encoding="UTF-8" ?>
<!--
引入dtd约束-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 是当前mapper对应的接口-->
<mapper namespace="com.etime.mapper.HusbandMapper">
<select id="getAllHusband" resultMap="husbandAndWife">
select * from wife w,husband h where w.wid=h.wid;
</select>
<resultMap id="husbandAndWife" type="Husband">
<id property="hid" column="hid"></id>
<result property="hname" column="hname"></result>
<result property="wid" column="wid"></result>
<association property="wife" javaType="Wife">
<id property="wid" column="wid"></id>
<result property="wname" column="wname"></result>
</association>
</resultMap>
</mapper>
(8)测试
package com.etime.test;
import com.etime.mapper.HusbandMapper;
import com.etime.pojo.Husband;
import com.etime.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MybatisTest {
@Test
public void test01(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
HusbandMapper husbandMapper = sqlSession.getMapper(HusbandMapper.class);
List<Husband> list = husbandMapper.getAllHusband();
list.forEach(System.out::println);
sqlSession.close();
}
}
// 结果
Husband(hid=1, hname=周瑜, wid=1, wife=Wife(wid=1, wname=小乔))
Husband(hid=2, hname=孙悟空, wid=2, wife=Wife(wid=2, wname= 露娜))
Husband(hid=3, hname=孙策, wid=3, wife=Wife(wid=3, wname=大乔))
Husband(hid=4, hname=刘备, wid=4, wife=Wife(wid=4, wname=孙尚香))
Husband(hid=5, hname=项羽, wid=5, wife=Wife(wid=5, wname=虞姬))
Process finished with exit code 0
二、一对多/多对一
1、创建表
- 以 学生表 和 班级表 为例
CREATE TABLE classes(
cid INT PRIMARY KEY AUTO_INCREMENT,
cname VARCHAR(10) NOT NULL
);
CREATE TABLE student(
sid INT PRIMARY KEY AUTO_INCREMENT,
sname VARCHAR(10) NOT NULL,
cid INT,
FOREIGN KEY(cid) REFERENCES classes(cid)
);
2、业务需求
- 查询出所有学生的信息及其所在班级的信息
# SQL语句查询
select * from classes c,student s where c.cid=s.cid;
3、代码示例编写
(1)方式1:多对一 使用resultMap来插叙
- 多:学生(主体)
- 一:班级
a.实体类编写
- 班级类
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Classes {
private int cid;
private String cname;
}
- 学生类(主体)
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
private int sid;
private String sname;
private int cid;
private Classes classes;
}
b.在 接口 StudentMapper.java 中定义方法
public interface StudentMapper {
List<Student> getAllStudent();
}
c.在 映射文件 StudentMapper.xml 中配置
<?xml version="1.0" encoding="UTF-8" ?>
<!--
引入dtd约束-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 是当前mapper对应的接口-->
<mapper namespace="com.etime.mapper.StudentMapper">
<select id="getAllStudent" resultMap="StudentAndClasses">
select * from classes c,student s where c.cid=s.cid;
</select>
<resultMap id="StudentAndClasses" type="Student">
<id property="sid" column="sid"></id>
<result property="sname" column="sname"></result>
<result property="cid" column="cid"></result>
<association property="classes" javaType="Classes">
<id property="cid" column="cid"></id>
<result property="cname" column="cname"></result>
</association>
</resultMap>
</mapper>
d.测试
@Test
public void test02(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list = studentMapper.getAllStudent();
list.forEach(System.out::println);
sqlSession.close();
}
// 结果
Student(sid=1, sname=李一, cid=1, classes=Classes(cid=1, cname=开发))
Student(sid=2, sname=李二, cid=1, classes=Classes(cid=1, cname=开发))
Student(sid=3, sname=张一, cid=1, classes=Classes(cid=1, cname=开发))
Student(sid=4, sname=张二, cid=2, classes=Classes(cid=2, cname=测试))
Student(sid=5, sname=张三, cid=2, classes=Classes(cid=2, cname=测试))
Student(sid=6, sname=李三, cid=2, classes=Classes(cid=2, cname=测试))
Student(sid=7, sname=李四, cid=3, classes=Classes(cid=3, cname=设计))
Process finished with exit code 0
(2)方式2:一对多 使用resultMap来插叙
- 一:班级(主体)
- 多:学生
a.实体类编写
- 学生类
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
private int sid;
private String sname;
private int cid;
}
- 班级类(主体)
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Classes {
private int cid;
private String cname;
private List<Student> studentList;
}
b.在 接口 ClassesMapper.java 中定义方法
package com.etime.mapper;
import com.etime.pojo.Classes;
import java.util.List;
public interface ClassesMapper {
List<Classes> getAllClasses();
}
c.在 映射文件 ClassesMapper.xml 中配置
<?xml version="1.0" encoding="UTF-8" ?>
<!--
引入dtd约束-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace 是当前mapper对应的接口-->
<mapper namespace="com.etime.mapper.ClassesMapper">
<select id="getAllClasses" resultMap="ClassesAndStudent">
select * from classes c,student s where c.cid=s.cid;
</select>
<resultMap id="ClassesAndStudent" type="Classes">
<id property="cid" column="cid"></id>
<result property="cname" column="cname"></result>
<collection property="studentList" ofType="Student">
<id property="sid" column="sid"></id>
<result property="sname" column="sname"></result>
<result property="cid" column="cid"></result>
</collection>
</resultMap>
</mapper>
d.测试
@Test
public void test03(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
ClassesMapper classesMapper = sqlSession.getMapper(ClassesMapper.class);
List<Classes> list = classesMapper.getAllClasses();
list.forEach(System.out::println);
sqlSession.close();
}
三、多对多
1、创建表
- 学生表 和 课程表 以及中间表
CREATE TABLE classes(
cid INT PRIMARY KEY AUTO_INCREMENT,
cname VARCHAR(10) NOT NULL
);
CREATE TABLE student(
sid INT PRIMARY KEY AUTO_INCREMENT,
sname VARCHAR(10) NOT NULL,
cid INT,
FOREIGN KEY(cid) REFERENCES classes(cid)
);
CREATE TABLE course(
courseid INT PRIMARY KEY AUTO_INCREMENT,
coursename VARCHAR(10) NOT NULL
);
CREATE TABLE studentcourse(
scid INT PRIMARY KEY AUTO_INCREMENT,
sid INT,
courseid INT,
FOREIGN KEY(sid) REFERENCES student(sid),
FOREIGN KEY(courseid) REFERENCES course(courseid)
);
2、业务需求
- 查询学生学习的课程
# SQL语句查询
select * from student s,course c,studentcourse sc where s.sid=sc.sid and c.courseid=sc.courseid;
3、示例代码编写
(1)方式1:无中间表实体类
a.实体类
- 课程类
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Course {
private int courseid;
private String coursename;
}
- 学生类 (主体)
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
private int sid;
private String sname;
private int cid;
private List<Course> courseList;
}
b.在 接口 StudentMapper.java 中定义方法
List<Student> getAllStudentAndCourse();
c.在 映射文件 StudentMapper.xml 中配置信息
<select id="getAllStudentAndCourse" resultMap="StudentAndCourse">
select * from student s,course c,studentcourse sc where s.sid=sc.sid and c.courseid=sc.courseid;
</select>
<resultMap id="StudentAndCourse" type="Student">
<id property="sid" column="sid"></id>
<result property="sname" column="sname"></result>
<result property="cid" column="cid"></result>
<collection property="courseList" ofType="Course">
<id property="courseid" column="courseid"></id>
<result property="coursename" column="coursename"></result>
</collection>
</resultMap>
d.测试
@Test
public void test04(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list = studentMapper.getAllStudentAndCourse();
list.forEach(System.out::println);
sqlSession.close();
}
// 结果
Student(sid=1, sname=李一, cid=1, courseList=[Course(courseid=1, coursename=Java高级语言), Course(courseid=2, coursename=JavaWeb), Course(courseid=3, coursename=JavaEE)])
Student(sid=2, sname=李二, cid=1, courseList=[Course(courseid=1, coursename=Java高级语言), Course(courseid=4, coursename=数据结构)])
Student(sid=3, sname=张一, cid=1, courseList=[Course(courseid=2, coursename=JavaWeb), Course(courseid=3, coursename=JavaEE)])
Process finished with exit code 0
(2)方式2:加入中间表
a.实体类
- 课程类
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Course {
private int courseid;
private String coursename;
}
- 中间表类(主体2)
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class StudentCourse {
private int scid;
private int sid;
private int courseid;
private Course course;
}
- 学生类(主体1)
package com.etime.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Student {
private int sid;
private String sname;
private int cid;
private List<StudentCourse> studentCourseList;
}
b.在接口 StudentMapper.java 文件中定义方法
List<Student> getAllStudentAndCourseByMindTable();
c.在映射文件 StudentMapper.xml 文件中 配置信息
- 注意:在测试时其他方法的配置信息可能出错,比如上个方法中的 courseList,因为实体类中属性发生了变动。
<select id="getAllStudentAndCourseByMindTable" resultMap="MindTable">
select * from student s,course c,studentcourse sc where s.sid=sc.sid and c.courseid=sc.courseid;
</select>
<resultMap id="MindTable" type="Student">
<id property="sid" column="sid"></id>
<result property="sname" column="sname"></result>
<result property="cid" column="cid"></result>
<collection property="studentCourseList" ofType="StudentCourse">
<id property="scid" column="scid"></id>
<result property="sid" column="sid"></result>
<result property="courseid" column="courseid"></result>
<association property="course" column="Course">
<id property="courseid" column="courseid"></id>
<result property="coursename" column="coursename"></result>
</association>
</collection>
</resultMap>
d.测试
@Test
public void test05(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> list = studentMapper.getAllStudentAndCourseByMindTable();
list.forEach(System.out::println);
sqlSession.close();
}
mybatis 延迟加载
- 目的:Mybatis优化性能。
一、什么是延迟加载
- 延迟加载(lazy load)是(也称为懒加载)关联关系对象默认的加载方式。
- 延迟加载机制是为了避免一些无谓的性能开销而提出来的。
- 延迟加载就是当在真正需要数据的时候,才真正执行数据加载操作
- 延迟加载,可以简单理解为,只有在使用的时候,才会发出sql语句进行查询。
二、为什么要使用延迟加载
- 减少访问数据库的频率
- 访问的数据量过大,明显缓存不太合适。因为内存容量有限为了减少并发量,减少系统资源的消耗
- 使用前提条件:、必须是嵌套方式
- 嵌套的是对象、集合等。例:association、collection 具备延迟加载功能。
三、局部延迟加载
- 在 映射文件 Mapper中设计延迟加载
四、全局延迟加载
- 在 mybatis核心配置文件 mybatisConfig.xml中配置
- 注意:标签的位置(dtd约束中体现)
<!--全局加载-->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
mybatis 逆向工程
一、mybatis 逆向工程概述
1、前言
我们企业开发中是先进行数据建模即建库建表并设定表和表之间的关系。可以举方活中的列子,如盖楼先有图纸,才能盖楼,而不是先盖楼再画图纸。
2、产生背景
mybatis 考虑到对单标进行 CRUD时,对于映射文件来说只是标签和SQL语句的不同,所以提供了 逆向工程,可以通过过表直接生成实体类、接口、接口的映射文件,来减轻开人员工作量,提高开发效率。
二、编写示例代码
1、构建maven项目,引入依赖,配置pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.etime</groupId>
<artifactId>generatorTest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>5.2.5.RELEASE</spring.version>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
2、创建数据源 jdbc.properties 属性文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_418
root=root
password=root
3、创建mybatis核心配置文件 mybatisConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--引入dtd约束-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置连接数据库的信息:动态的读-->
<properties resource="jdbc.properties"></properties>
<!--全局加载-->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<!--给实体类取别名-->
<typeAliases>
<package name="com.etime.pojo"/>
</typeAliases>
<!--配置mybatis的环境-->
<environments default="development">
<!--配置环境-->
<environment id="development">
<!--配置事务的类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置链接数据库的信息:使用的是 数据源[连接池]-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${root}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--注册映射文件位置-->
<mappers>
<package name="com.etime.mapper"/>
</mappers>
</configuration>
4、创建 逆向工程核心配置文件 generatorConfig.xml
<?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="testTables" targetRuntime="mybatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/db_418"
userId="root" password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成实体类的位置 -->
<javaModelGenerator targetPackage="com.etime.pojo" targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.etime.mapper" targetProject=".\src\main\resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.etime.mapper" targetProject=".\src\main\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="classes"></table>
<table tableName="course"></table>
<table tableName="husband"></table>
<table tableName="studentcourse"></table>
<table tableName="student"></table>
<table tableName="wife"></table>
</context>
</generatorConfiguration>
5、根据逆向工程 API 编写代码
package com.etime.test;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class TestDemo {
@Test
public void test01(){
File file = new File("F:\\mavenProject\\generatorTest\\src\\main\\resources\\ generatorConfig.xml");
List<String> list = new ArrayList<>();
ConfigurationParser configurationParser = new ConfigurationParser(list);
try {
Configuration configuration = configurationParser.parseConfiguration(file);
DefaultShellCallback defaultShellCallback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration,defaultShellCallback,list);
myBatisGenerator.generate(null);
} catch (IOException e) {
e.printStackTrace();
} catch (XMLParserException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
6、逆向工程测试结果
7、根据逆向工程生成的文件进行相关操作
package com.etime.test;
import com.etime.mapper.StudentMapper;
import com.etime.pojo.Student;
import com.etime.pojo.StudentExample;
import com.etime.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class GeneratorTest {
// 查询所有学生
@Test
public void test01(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
StudentExample studentExample = new StudentExample();
List<Student> list = studentMapper.selectByExample(studentExample);
list.forEach(System.out::println);
sqlSession.close();
}
// 根据主键查询学生信息
@Test
public void test02(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = studentMapper.selectByPrimaryKey(1);
System.out.println(student);
sqlSession.close();
}
// 根据其他信息查询学生,例:根据学生班级查询学生
@Test
public void test03(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
StudentExample studentExample = new StudentExample();
// 创建条件对象
StudentExample.Criteria criteria = studentExample.createCriteria();
criteria.andCidEqualTo(1);
List<Student> list = studentMapper.selectByExample(studentExample);
list.forEach(System.out::println);
sqlSession.close();
}
// 新增学生
@Test
public void test04(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setSid(0);
student.setSname("tom");
student.setCid(1);
int res = studentMapper.insert(student);
System.out.println("add res = " + res);
sqlSession.close();
}
// 根据主键修改学生
@Test
public void test05(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setSid(8);
student.setSname("狮子王");
student.setCid(1);
int res = studentMapper.updateByPrimaryKey(student);
System.out.println("update res = " + res);
sqlSession.close();
}
// 根据主键删除学生
@Test
public void test06(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
int res = studentMapper.deleteByPrimaryKey(8);
System.out.println("delete res = " + res);
sqlSession.close();
}
}
dent.setSid(0);
student.setSname(“tom”);
student.setCid(1);
int res = studentMapper.insert(student);
System.out.println("add res = " + res);
sqlSession.close();
}
// 根据主键修改学生
@Test
public void test05(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = new Student();
student.setSid(8);
student.setSname("狮子王");
student.setCid(1);
int res = studentMapper.updateByPrimaryKey(student);
System.out.println("update res = " + res);
sqlSession.close();
}
// 根据主键删除学生
@Test
public void test06(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
int res = studentMapper.deleteByPrimaryKey(8);
System.out.println("delete res = " + res);
sqlSession.close();
}
}