SpringBoot整合Mybatis之xml
SpringBoot整合Mybatis
mybatis
ORM框架.几个重要的概念:
- Mapper配置 : 可以使用基于XML的Mapper配置文件来实现,也可以使用基于Java注解的Mybatis注解来实现,甚至可以直接使用Mybatis提供的API实现.
- Mapper接口 : 自行定义的一个数据操作接口,也就是通常说的DAO接口.早期接口需要自己自定义实现,现在Mybatis会自动为Mpper接口创建动态代理对象. Mapper接口的方法通常与Mapper配置文件中的select,insert,update,delete等XML结点存在--对应关系
- Executor : Mybatis中所有的Mapper语句都是通过Executor进行的,Executor是Mybatis的一个核心接口.
- SqlSession : 是Mybatis的关键对象,是执行持久化操作的独享.SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法,它的底层封装了JDBC连接,可以用SqlSession案例来直接执行被映射的SQL语句.
- SqlSessionFactory : 是Mybatis的关键对象,是单个数据库映射关系经过编译后的内存镜像. SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象获得,而SqlSessionFactoryBuilder则可以从XML配置文件和一个预先定制的Configuration的实例构建出来.
工作流程 :
- 首先加载 Mapper 配置的 SQL 映射文件,或者是注解的相关 SQL 内容。
- 创建会话工厂,MyBatis 通过读取配置文件的信息来构造出会话工厂(SqlSessionFactory)。
- 创建会话。根据会话工厂,MyBatis 就可以通过它来创建会话对象(SqlSession),会话对象是一个接口,该接口中包含了对数据库操作的增、删、改、查方法。
- 创建执行器。因为会话对象本身不能直接操作数据库,所以它使用了一个叫做数据库执行器(Executor)的接口来帮它执行操作。
- 封装 SQL 对象。在这一步,执行器将待处理的 SQL 信息封装到一个对象中(MappedStatement),该对象包括 SQL 语句、输入参数映射信息(Java 简单类型、HashMap 或 POJO)和输出结果映射信息(Java 简单类型、HashMap 或 POJO)。
- 操作数据库。拥有了执行器和 SQL 信息封装对象就使用它们访问数据库了,最后再返回操作结果,结束流程。
加载接口,SqlSessionFactoryBuilder构建SqlSessionFactory,SqlSessionFactory创建爱你Sqsession,SqlSession创建Executor,Executor封装SQL对象,最后再操作数据库,返回操作结果,结束.
SpringBoot集成Mybatis
- 引入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
- 添加配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://39.105.167.131:3306/smile_boot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: Nrblwbb7$
mybatis:
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: con.mybatis.springboot_mybatis.model
- mybatis.config-location,配置 mybatis-config.xml 路径,mybatis-config.xml 中配置 MyBatis 基础属性;
- mybatis.mapper-locations,配置 Mapper 对应的 XML 文件路径;
- mybatis.type-aliases-package,配置项目中实体类包路径;
- spring.datasource.*,数据源配置。
Spring Boot 启动时数据源会自动注入到 SqlSessionFactory 中,使用 SqlSessionFactory 构建 SqlSession,再自动注入到 Mapper 中,最后我们直接使用 Mapper 即可。
- 启动类添加注解
@SpringBootApplication
@MapperScan("com.mybatis.springboot_mybatis.mapper")
public class SpringbootMybatisApplication {
}
- mybatis-config.xml的配置
mybatis-config.xml 主要配置常用的 typeAliases,设置类型别名,为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
- 编写代码进行测试
model类(也就是实体类,对性别进行了枚举)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String userName;
private String passWord;
private UserSexEnum userSex;
private String nickName;
public User() {
super();
}
public User(String userName, String passWord, UserSexEnum userSex) {
super();
this.passWord = passWord;
this.userName = userName;
this.userSex = userSex;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public UserSexEnum getUserSex() {
return userSex;
}
public void setUserSex(UserSexEnum userSex) {
this.userSex = userSex;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", userSex=" + userSex +
", nickName='" + nickName + '\'' +
'}';
}
}
枚举类:
public enum UserSexEnum {
MAN, WOMAN
}
操作类(也就是实体的简化类还有其他的分页实体类,也就是平常所说的vm):
public class UserParam extends PageParam{
private String userName;
private String userSex;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
}
public class PageParam {
private int beginLine; //起始行
private Integer pageSize = 3;
private Integer currentPage=0; // 当前页
public int getBeginLine() {
return pageSize*currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
@Override
public String toString() {
return "PageParam{" +
"beginLine=" + beginLine +
", pageSize=" + pageSize +
", currentPage=" + currentPage +
'}';
}
}
0代表第一页,1代表第2页
mapper类 :
public interface UserMapper {
List<User> getAll();
List<User> getList(UserParam userParam);
int getCount(UserParam userParam);
User getOne(Long id);
void insert(User user);
int update(User user);
int delete(Long id);
}
mapper的xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.mybatis.springboot_mybatis.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.mybatis.springboot_mybatis.model.User" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="passWord" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex" javaType="com.mybatis.springboot_mybatis.enums.UserSexEnum"/>
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, userName, passWord, user_sex, nick_name
</sql>
<sql id="Base_Where_List">
<if test="userName != null and userName != ''">
and userName = #{userName}
</if>
<if test="userSex != null and userSex != ''">
and user_sex = #{userSex}
</if>
</sql>
<select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
</select>
<select id="getList" resultMap="BaseResultMap" parameterType="com.mybatis.springboot_mybatis.param.UserParam">
select
<include refid="Base_Column_List" />
from users
where 1=1
<include refid="Base_Where_List" />
order by id desc
limit #{beginLine} , #{pageSize}
</select>
<select id="getCount" resultType="Integer" parameterType="com.mybatis.springboot_mybatis.param.UserParam">
select
count(1)
from users
where 1=1
<include refid="Base_Where_List" />
</select>
<select id="getOne" parameterType="Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.mybatis.springboot_mybatis.model.User" >
INSERT INTO
users
(userName,passWord,user_sex)
VALUES
(#{userName}, #{passWord}, #{userSex})
</insert>
<update id="update" parameterType="com.mybatis.springboot_mybatis.model.User" >
UPDATE
users
SET
<if test="userName != null">userName = #{userName},</if>
<if test="passWord != null">passWord = #{passWord},</if>
nick_name = #{nickName}
WHERE
id = #{id}
</update>
<delete id="delete" parameterType="Long" >
DELETE FROM
users
WHERE
id =#{id}
</delete>
</mapper>
注意修改自己的包名和接口路径等等,这里不考虑多数据源,多数据源看pdf
测试类
@SpringBootTest
@RunWith(SpringRunner.class)
public class MybatisXmlTest {
@Resource
private UserMapper userMapper;
@Test
public void testInsert() {
userMapper.insert(new User("aa", "a123456", UserSexEnum.MAN));
userMapper.insert(new User("bb", "b123456", UserSexEnum.WOMAN));
userMapper.insert(new User("cc", "b123456", UserSexEnum.WOMAN));
Assert.assertEquals(3, userMapper.getAll().size());
}
@Test
public void testUpdate() {
long id=1l;
User user = userMapper.getOne(id);
if(user!=null){
System.out.println(user.toString());
user.setNickName("wzlove");
userMapper.update(user);
Assert.assertTrue(("wzlove".equals(userMapper.getOne(id).getNickName())));
}else {
System.out.println("not find user id="+id);
}
}
@Test
public void testDelete() {
int count=userMapper.delete(3l);
if(count>0){
System.out.println("delete is sucess");
}else {
System.out.println("delete if failed");
}
}
@Test
public void findAll(){
UserParam userParam = new UserParam();
userParam.setCurrentPage(0);
userParam.setPageSize(1);
List<User> list = userMapper.getList(userParam);
System.out.println(list.get(0));
Assert.assertEquals(1,list.size());
}
}