SpringBoot:4.SpringBoot整合Mybatis實現數據庫訪問

在公司項目開發中,使用Mybatis居多。在 SpringBoot:3.SpringBoot使用Spring-data-jpa實現數據庫訪問 中,這種jpa風格的把sql語句和java代碼放到一塊兒,總感受分離的不夠完全。基於我的習慣,仍是比較喜歡把代碼和sql分開,sql語句在xml文件裏無論多複雜,寫到xml裏看起來比較簡單,不是那麼臃腫。java

1.整合Mybatis

1.1 添加pom.xml依賴

主要就四個依賴:mysql

spring-boot-starter-test、spring-boot-starter:用於作單元測試git

mybatis-spring-boot-starter:Mybatis核心依賴github

mysql-connector-java:Mysql依賴,訪問數據庫spring

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency> 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- 引入MySQL鏈接的依賴包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

1.2 配置數據庫信息

在application.properties 配置相關mysql信息sql

#數據庫配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#mybatis放置xml文件的地方,咱們配置在classpath下的mapper文件夾下
mybatis.mapper-locations=classpath*:mapper/*.xml

1.3 建立user表

經過下面的sql語句建立user表信息:包括id、name(名字)、age(年齡)。數據庫

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

1.4 建立實體類

建立user表的映射實體類。apache

package com.w3cjava.entity;
public class User {
    private Long id;

    private String name;

    private Integer age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }   
}

1.5 數據訪問層Dao

建立User實體類的UserDao層,實現簡單的增刪改查操做。微信

package com.w3cjava.dao;

import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.w3cjava.entity.User;

@Mapper
public interface UserDao{
    int insert(@Param("name") String name, @Param("age") Integer age);

    /**
     * 
     * @author cos
     * @desc 經過Map<String, Object>對象來做爲傳遞參數的容器
     * @param map
     * @return
     */
    int insertByMap(Map<String, Object> map);
    /**
     * 
     * @author cos
     * @desc 使用對象
     * @param user
     * @return
     */
    
    int insert(User user);
    
    void update(User user);

    void delete(Long id);
    /**
     * 
     * @author cos
     * @desc 返回結果的綁定
     * @return
     */
    List<User> findAll();    
    /**
     * 
     * @author cos
     * @desc 使用@Param傳參,@Param中定義的name對應了SQL中的#{name},age對應了SQL中的#{age}
     * @param name
     * @return
     */
    User findByName(@Param("name") String name);
}

1.6 數據訪問xml映射

經過mybatis.mapper-locations=classpath:mapper/.xml配置,咱們將在classpath路徑的mapper文件夾下建立UserDao對應的映射xml。mybatis

<?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.w3cjava.dao.UserDao">
    <sql id="testColumns">
        a.id AS "id",
        a.name AS "name",
        a.age AS "age"
    </sql>
    
    <sql id="testJoins">
    </sql>
    <!-- 查詢全部user -->
     <select id="findByName" resultType="com.w3cjava.entity.User">
            select 
                <include refid="testColumns"/>
             from user a 
             WHERE a.name = #{name}
     </select>  
     
    <!-- 查詢全部user -->
     <select id="findAll" resultType="com.w3cjava.entity.User">
            select 
                <include refid="testColumns"/>
             from user a 
     </select>       
         
    <insert id="insert">
        INSERT INTO user(
            name,
            age
        ) VALUES (
            #{name},
            #{age}
            )
    </insert>
    
    <insert id="insertByMap">
        INSERT INTO user(
            name,
            age
        ) VALUES (
            #{name,jdbcType=VARCHAR},
            #{age,jdbcType=INTEGER}
            )
    </insert>
    <update id="update">
        UPDATE user SET age=#{age} WHERE name=#{name}
    </update>
    <delete id="delete">
        DELETE FROM user WHERE id =#{id}
    </delete>    
</mapper>

2.應用啓動類

建立應用主類。@EnableTransactionManagement之因此加上這個註解,是爲了後面每個單元測試時使用回顧註解,保證數據庫數據測試完成後不被污染。以便開始下一個測試。

package com.w3cjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
 * 
 * @class  SpringBootMybatisApplication
 * @version SpringBoot 2.1.9
 * @author cos
 * @desc   整合Mybatis
 *
 */
@SpringBootApplication
@EnableTransactionManagement
public class SpringBootMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatisApplication.class, args);
    }

}

3.單元測試

測試基本邏輯:

  • 向數據庫中插入數據
  • 查詢部分數據
  • 經過使用@Rollback、@Transactional回滾數據,保證每一次單元測試數據的獨立性。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringBootMybatisApplication.class})
public class UserServiceTest {
    @Autowired
    private UserDao userDao;
    @Test
    @Transactional
    @Rollback
    public void insert() throws Exception {
        userDao.insert("AAA", 20);
    }
    
    @Test
    @Transactional
    @Rollback
    public void findByName() throws Exception {
        userDao.insert("AAA", 20);
        User u = userDao.findByName("AAA");
        Assert.assertEquals(20, u.getAge().intValue());
    }
    
    @Test
    @Transactional
    @Rollback
    public void testMap() throws Exception{
        Map<String, Object> map = new HashMap<>();
        map.put("name", "CCC");
        map.put("age", 40);
        userDao.insertByMap(map);
    }
    
    
    @Test
    @Transactional
    @Rollback
    public void testuserDao() throws Exception {
        // insert一條數據,並select出來驗證
        userDao.insert("AAA", 20);
        User u = userDao.findByName("AAA");
        Assert.assertEquals(20, u.getAge().intValue());
        // update一條數據,並select出來驗證
        u.setAge(30);
        userDao.update(u);
        u = userDao.findByName("AAA");
        Assert.assertEquals(30, u.getAge().intValue());
        // 刪除這條數據,並select驗證
        userDao.delete(u.getId());
        u = userDao.findByName("AAA");
        Assert.assertEquals(null, u);
    }
    
    
    @Test
    @Transactional
    @Rollback
    public void testSelectMapper() throws Exception {
        List<User> userList = userDao.findAll();
        for(User user : userList) {
            Assert.assertEquals(null, user.getId());
            Assert.assertNotEquals(null, user.getName());
        }
    }
}

4.參考文章

spring-test @Rollback回滾: https://www.jianshu.com/p/3b2...

5.文章源碼

04.Spring-Boot-Mybatis
歡迎掃面下列二維碼關注「餘弦的自留地」公衆微信號
在這裏插入圖片描述萬物之中,但願至美

相關文章
相關標籤/搜索