1. 程式人生 > >Spring Boot快速入門(五):使用MyBatis(註解形式)進行資料庫操作

Spring Boot快速入門(五):使用MyBatis(註解形式)進行資料庫操作

新增依賴

新建專案選擇web,MyBatis,MySQL三個依賴

對於已存在的專案可以在bulid.gradle加入,spring boot將會幫你自動配置好

compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-web')
runtime('mysql:mysql-connector-java')
testCompile('org.springframework.boot:spring-boot-starter-test')

配置基本資訊

然後在src/main/resources/application.properties下新增基本配置

#資料庫連線地址
spring.datasource.url=jdbc:mysql://localhost:3306/mybaits?useSSL=false
#資料庫賬號
spring.datasource.username=root
#資料庫密碼
spring.datasource.password=123456zxc
#資料庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

建立實體

建立一個User實體,包含id、name(姓名)、age(年齡)屬性

public class User
{
    private Long id;
    private String name;
    private Integer age;

    public User()
    {
    }

    public User(String name, Integer 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;
    }
}


建立資料訪問介面
建立一個userMapper介面,進行資料庫操作,新增@Mapper註解

import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper//這是一個MyBatis的資料庫操作介面
public interface UserMapper
{
    @Select("SELECT * FROM user WHERE name = #{name}")
    User findByName(@Param("name") String name);

    @Select("SELECT * FROM user WHERE name LIKE #{name}")
    List<User> findByNameLike(@Param("name") String name);

    @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Update("UPDATE user SET age = #{age} WHERE name = #{name}")
    int update(@Param("name") String name, @Param("age") Integer age);

    @Delete("DELETE FROM user WHERE name = #{name}")
    int delete(@Param("name") String name);

    @Select("SELECT COUNT(*) FROM user")
    int countAll();
}

單元測試

在src/test/java/你的包名/你的專案名ApplicationTests編寫對應的單元測試來驗證編寫的內容是否正確

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional//宣告事務,配合Rollback
public class MybatisApplicationTests
{
    @Autowired
    private UserMapper userMapper;

    @Test
    @Rollback//測試結束回滾資料,保證測試單元每次執行的資料環境獨立
    public void testUser()
    {
        userMapper.insert("QQQ",1);
        userMapper.insert("WWW",2);
        userMapper.insert("EEE",3);
        userMapper.insert("AAA",4);
        userMapper.insert("SSS",5);
        userMapper.insert("DDD",6);
        userMapper.insert("ZZZ",7);
        userMapper.insert("XXX",8);
        userMapper.insert("CCC",9);
        userMapper.insert("SSS213",10);

        // 測試findAll, 查詢所有記錄
        Assert.assertEquals(10, userMapper.countAll());

        // 測試findByName, 查詢姓名為AAA的User
        Assert.assertEquals(4, userMapper.findByName("AAA").getAge().longValue());

        // 更新CCC使用者的年齡為15
        userMapper.update("CCC",15);

        // 測試findByName, 查詢姓名為CCC的User的年齡是否為15
        Assert.assertEquals(15, userMapper.findByName("CCC").getAge().longValue());

        // 測試刪除姓名為AAA的User
        userMapper.delete("AAA");

        // 測試findAll, 查詢所有記錄, 驗證上面的刪除是否成功
        Assert.assertEquals(9, userMapper.countAll());

        // 測試findAll, 查詢名字有S的有幾個
        Assert.assertEquals(2,userMapper.findByNameLike("%S%").size());
    }

}

測試結果