1. 程式人生 > >spring-boot 整合mybatis配置使用

spring-boot 整合mybatis配置使用

新增maven依賴

在pom檔案中增加如下內容

<dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.1.1</version>
</dependency>

建立表

在資料庫中增加一張表用於測試,以下是建表語句

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
  `name` varchar(128) DEFAULT NULL,
  `money` decimal(10,2) DEFAULT NULL,
  `create_date` datetime NOT NULL,
  `modify_date` datetime NOT NULL,
  `is_deleted` tinyint(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='使用者';

新增相關配置資訊

首先在resources目錄下增加mybatis-config.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>
    <mappers>
        <mapper resource="mybatis/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
在resources目錄下建立mybatis/mapper目錄,並在其下建立UserMapper.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.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.model.UserMo">
        <id column="id" jdbcType="BIGINT" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="money" jdbcType="DECIMAL" property="money" />
        <result column="create_date" jdbcType="TIMESTAMP" property="createDate" />
        <result column="modify_date" jdbcType="TIMESTAMP" property="modifyDate" />
        <result column="is_deleted" jdbcType="TINYINT" property="isDeleted" />
    </resultMap>
    <select id="selectUserById" resultMap="BaseResultMap">
        select * from test_user where id = #{id}
    </select>
</mapper>

在application.propertise檔案中新增以下配置,指定mybatis-config.xml的位置

mybatis.config-location=classpath:mybatis-config.xml
如果在application.propertise檔案中新增以下配置,則mybatis-config.xml無需再配置<mappers></mappers>中的內容
mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml

相關java程式碼

建立表user對應的實體類UserMo.java

package com.model;

import java.math.BigDecimal;
import java.util.Date;

public class UserMo {

    private Long id;
    private String name;
    private BigDecimal money;
    private Date createDate;
    private Date modifyDate;
    private Integer isDeleted;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getMoney() {
        return money;
    }

    public void setMoney(BigDecimal money) {
        this.money = money;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }

    public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }
}
建立對應的UserMapper.java
package com.mapper;

import com.model.UserMo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserMapper {

    UserMo selectUserById(@Param("id") Long id);
}
建立UserDao.java
package com.dao;

import com.model.UserMo;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Component;

@Component
public class UserDao {

    private final SqlSession sqlSession;

    public UserDao(SqlSession sqlSession) {
        this.sqlSession = sqlSession;
    }

    public UserMo findUserById(Long id) {
        return this.sqlSession.selectOne("selectUserById", id);
    }
}

測試

OK,準備工作都已就緒,開始測試,增加如下內容

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDao userDao;

    @RequestMapping("/find/mybatis/id")
    public String findMailByToFromMybatis(HttpServletRequest request, Long id) {
        UserMo userMo = userMapper.selectUserById(id);
        UserMo userMo1 = userDao.findUserById(id);
        return "userMapper: " + JSON.toJSONString(userMo) + ", userDao: " + JSON.toJSONString(userMo1);
    }
啟動專案,在瀏覽器中輸入http://127.0.0.1:8080/find/mybatis/id?id=1,會看到如下
userMapper: {"createDate":1483586613000,"id":1,"isDeleted":0,"modifyDate":1483586613000,"money":1.20,"name":"sss"} 
userDao: {"createDate":1483586613000,"id":1,"isDeleted":0,"modifyDate":1483586613000,"money":1.20,"name":"sss"}
而且在控制檯看到如下輸出
INFO 1238 --- [nio-8080-exec-1] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
[http-nio-8080-exec-1] INFO  c.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
可以看到用的連線池正是之前配置的druid連線池。

其中很多程式碼入model,mapper等可以通過mybatis的逆向工程直接生成。

另一種方式

使用Mapper註解,不需要對應的mapper.xml檔案,建立UserMapper1.java

package com.mapper;

import com.model.UserMo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper1 {

    @Select("select id, name, money, create_date as createDate, modify_date as modifyDate, is_deleted as isDeleted" +
            " from test_user where name = #{name}")
    UserMo selectUserByName(@Param("name") String name);
}
其中部分欄位使用了別名,不這樣的話無法得到其中的內容。

測試程式碼如下

    @Autowired
    private UserMapper1 userMapper1;

    @RequestMapping("/find/mybatis/name")
    public String findMailByToFromMybatis(HttpServletRequest request, String name) {
        UserMo userMo = userMapper1.selectUserByName(name);
        return "userMapper1: " + JSON.toJSONString(userMo);
    }
啟動服務後,輸入http://127.0.0.1:8080/find/mybatis/name?name=sss,可以看到如下內容
userMapper1: {"createDate":1483586613000,"id":1,"isDeleted":0,"modifyDate":1483586613000,"money":1.20,"name":"sss"}