首页 > 代码库 > Spring boot 学习笔记 (二)- 整合MyBatis

Spring boot 学习笔记 (二)- 整合MyBatis

Spring boot 学习笔记 (二)- 整合MyBatis

 

Spring Boot中整合MyBatis,并通过注解方式实现映射。

整合MyBatis

以Spring boot 学习笔记 (一)- Hello world 为基础项目,在pom.xml中添加如下依赖

 

<dependency>  <groupId>org.mybatis.spring.boot</groupId>  <artifactId>mybatis-spring-boot-starter</artifactId>  <version>1.1.1</version></dependency><dependency>  <groupId>mysql</groupId>   <artifactId>mysql-connector-java</artifactId>   <version>5.1.21</version></dependency>

在application.properties 文件下 添加mysql的连接配置(切记不要在行尾留有空格,否则报com.mysql.jdbc.Driver   Class Not Found error,其实只是含有空格导致找不到类)

spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=spring.datasource.driver-class-name=com.mysql.jdbc.Driver

同其他Spring Boot工程一样,简单且简洁的的完成了基本配置,下面看看如何在这个基础下轻松方便的使用MyBatis访问数据库。

添加com.latteyan.entity包,并添加User 类

package com.latteyan.entity;import java.io.Serializable;public class User implements Serializable{        private static final long serialVersionUID = 8002149736589557777L;    private Long id;        private String name;        private Integer 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;    }}

添加com.latteyan.dao包,并添加UserMapper接口

package com.latteyan.dao;import java.util.List;import java.util.Map;import com.latteyan.entity.User;import org.apache.ibatis.annotations.*;@Mapperpublic interface UserMapper {    // 通过Parameter新增    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")    int insertByParameter(@Param("name") String name, @Param("age") Integer age);        // 通过Map新增    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")    int insertByMap(Map<String, Object> map);          // 通过Object新增    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")    int insertByObject(User user);        // Delete By Id    @Delete("DELETE FROM user WHERE id =#{id}")    void delete(Long id);        // Update    @Update("UPDATE user SET age=#{age} WHERE name=#{name}")    void update(User user);        // Find by Parameter    @Select("SELECT * FROM USER WHERE NAME = #{name}")    User findByName(@Param("name") String name);        // 通过@Results,绑定返回值    @Results({        @Result(property = "name", column = "name"),        @Result(property = "age", column = "age")    })    @Select("SELECT name, age FROM user")    List<User> findAll();  }
通过UserMapper 接口我们就可以现在访问数据库的功能.

单元测试
package com.latteyan;import java.util.HashMap;import java.util.List;import java.util.Map;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.context.junit4.SpringRunner;import com.latteyan.dao.UserMapper;import com.latteyan.entity.User;@RunWith(SpringRunner.class)@SpringBootTestpublic class SpringbootApplicationTests {    @Autowired    private UserMapper userMapper;    @Test    public void add() throws Exception {        // insert by parameter        userMapper.insertByParameter("zhangShan", 20);                // insert by object        User user = new User();        user.setAge(21);        user.setName("LiSi");        userMapper.insertByObject(user);                // insert by map        Map<String, Object> map = new HashMap<>();        map.put("name", "huangwu");        map.put("age", 22);        userMapper.insertByMap(map);                User zhangShan = userMapper.findByName("zhangShan");        Assert.assertEquals(20, zhangShan.getAge().intValue());        User LiSi = userMapper.findByName("LiSi");        Assert.assertEquals(21, LiSi.getAge().intValue());        User huangwu = userMapper.findByName("huangwu");        Assert.assertEquals(22, huangwu.getAge().intValue());    }        @Test    public void udpate() throws Exception {        User user = userMapper.findByName("zhangShan");        user.setAge(50);        userMapper.update(user);                user = userMapper.findByName("zhangShan");        Assert.assertEquals(50, user.getAge().intValue());                userMapper.delete(user.getId());    }        @Test    public void findAll() throws Exception {        List<User> users = userMapper.findAll();        Assert.assertNotNull(users);    }}

参考:http://blog.didispace.com/springbootmybatis/

 

Spring boot 学习笔记 (二)- 整合MyBatis