mybatis-spring-boot-starter主要有两种解决方案,一种是使用注解,一种是使用XML。
参考这篇文章动手跑了一个例子,稍微不同之处,原文是spring boot,这里改成了spring boot 2,mybatis现在最新版本为1.3.2。
一、使用注解
1、添加相关maven文件
<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.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
mybatis-spring-boot-starter最新版本可在官网查询
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html
2、application.properties 添加相关配置
mybatis.type-aliases-package = com.example.demo.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password =
3、实体类User.java
package com.example.demo.entity; import com.example.demo.enums.UserSexEnum; public class User { public User() { super(); } public User(String name, UserSexEnum sex) { super(); this.name = name; this.sex = sex; } private Integer id; private String name; private UserSexEnum sex; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public UserSexEnum getSex() { return sex; } public void setSex(UserSexEnum sex) { this.sex = sex; } @Override public String toString() { return "name " + this.name + ", sex " + this.sex; } }
4、枚举UserSexEnum.java
package com.example.demo.enums; public enum UserSexEnum { MAN, WOMAN }
5、启动类中添加对mapper包扫描@MapperScan,这样就不需要在每个Mapper类上面添加注解@Mapper。
package com.example.demo; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication @MapperScan("com.example.demo.mapper") public class DemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
6、开发Mapper
package com.example.demo.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.example.demo.entity.User; import com.example.demo.enums.UserSexEnum; public interface UserMapper { @Select("SELECT * FROM user") //结果集,关联实体类属性和数据库字段一一对应,如果两边一致,就不需要这个属性来修饰。 @Results({ @Result(property = "sex", column = "sex", javaType = UserSexEnum.class), }) List<User> getAll(); @Select("SELECT * FROM user WHERE id = #{id}") @Results({ @Result(property = "sex", column = "sex", javaType = UserSexEnum.class), }) User getOne(Long id); @Insert("INSERT INTO user(name,sex) VALUES(#{name}, #{sex})") void insert(User user); @Update("UPDATE user SET name=#{name} WHERE id =#{id}") void update(User user); @Delete("DELETE FROM user WHERE id =#{id}") void delete(Long id); }
7、单元测试
package com.example.demo.mapper; import java.util.List; 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.example.demo.entity.User; import com.example.demo.enums.UserSexEnum; @RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest { @Autowired private UserMapper UserMapper; @Test public void testInsert() throws Exception { UserMapper.insert(new User("aa", UserSexEnum.MAN)); UserMapper.insert(new User("bb", UserSexEnum.WOMAN)); UserMapper.insert(new User("cc", UserSexEnum.WOMAN)); Assert.assertEquals(3, UserMapper.getAll().size()); } @Test public void testQuery() throws Exception { List<User> users = UserMapper.getAll(); if(users==null || users.size()==0){ System.out.println("is null"); }else{ System.out.println(users.toString()); } } @Test public void testUpdate() throws Exception { User user = UserMapper.getOne(6l); System.out.println(user.toString()); user.setName("dd"); UserMapper.update(user); Assert.assertTrue(("dd".equals(UserMapper.getOne(6l).getName()))); } }
8、控制层
package com.example.demo.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; @RestController public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/getUsers") public List<User> getUsers() { List<User> users=userMapper.getAll(); return users; } @RequestMapping("/getUser") public User getUser(Long id) { User user=userMapper.getOne(id); return user; } @RequestMapping("/add") public void save(User user) { userMapper.insert(user); } @RequestMapping(value="update") public void update(User user) { userMapper.update(user); } @RequestMapping(value="/delete/{id}") public void delete(@PathVariable("id") Long id) { userMapper.delete(id); } }
项目目录结构:
二、使用XML
1、application.properties新增以下配置
mybatis.config-location = classpath:mybatis/mybatis-config.xml mybatis.mapper-locations = classpath:mybatis/mapper/*.xml
2、在resources/mybatis目录下添加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> <settings> <!-- 控制台打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <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>
3、添加映射文件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.example.demo.mapper.UserMapper" > <resultMap id="BaseResultMap" type="com.example.demo.entity.User" > <id column="id" property="id" jdbcType="BIGINT" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="sex" property="sex" javaType="com.example.demo.enums.UserSexEnum"/> </resultMap> <sql id="Base_Column_List" > id, name, sex </sql> <select id="getAll" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM user </select> <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" > SELECT <include refid="Base_Column_List" /> FROM user WHERE id = #{id} </select> <insert id="insert" parameterType="com.example.demo.entity.User" > INSERT INTO user (name,sex) VALUES (#{name}, #{sex}) </insert> <update id="update" parameterType="com.example.demo.entity.User" > UPDATE user SET name = #{name} WHERE id = #{id} </update> <delete id="delete" parameterType="java.lang.Long" > DELETE FROM user WHERE id =#{id} </delete> </mapper>
4、编写Dao层的代码
package com.example.demo.mapper; import java.util.List; import com.example.demo.entity.User; public interface UserMapper { List<User> getAll(); User getOne(Long id); void insert(User user); void update(User user); void delete(Long id); }
项目目录结构: