springboot整合mybatis
1、单纯使用注解进行配置
在pom文件中添加相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis -->
<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.46</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
编辑application.properties文件
mybatis.type-aliases-package=cn.xupengzhuang.entity
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中。
启动类中添加对mapper包扫描
@SpringBootApplication
@MapperScan("cn.xupengzhuang.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在数据库创建一张表,用于测试
CREATE TABLE `user` (
`user_id` int(10) NOT NULL AUTO_INCREMENT,
`user_name` varchar(15) NOT NULL,
`password` varchar(30) NOT NULL,
`age` int(2) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
根据表的字段,创建实体类
private Integer userId;
private String userName;
private String password;
private Integer age;
public User() {
}
public User(Integer userId, String userName, String password, Integer age) {
this.userId = userId;
this.userName = userName;
this.password = password;
this.age = age;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
编写Mapper文件
public interface UserMapper {
/**
* 查询所有
*/
@Select("select * from user")
@Results({
@Result(property = "userId",column = "user_id"),
@Result(property = "userName",column = "user_name")
})
List<User> getAllUsers();
/**
* 根据主键查询
*/
@Select("select * from user where user_id = #{id}")
@Results({
@Result(property = "userId",column = "user_id"),
@Result(property = "userName",column = "user_name")
})
User getUserById(@Param("id") Integer id);
/**
* 添加
*/
@Insert("insert into user values(#{userId},#{userName},#{password},#{age})")
int addUser(User user);
/**
* 删除
*/
@Delete("delete from user where user_id = #{id}")
int deleteUser(@Param("id") Integer id);
/**
* 修改
*/
@Update("update user set user_name=#{userName},password=#{password},age=#{age} where user_id = #{userId}")
int updateUser(User user);
}
开发Controller
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/getAllUsers")
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
@GetMapping("/getUser/{id}")
public User getUserById(@PathVariable("id") Integer id) {
return userMapper.getUserById(id);
}
/**
*
* 请使用接口测试工具进行测试
*/
@PostMapping("/addUser")
public String addUser() {
User user = new User();
user.setUserName("zxp");
user.setPassword("666");
user.setAge(23);
int i = userMapper.addUser(user);
if (i > 0) {
return "success";
} else {
return "fail";
}
}
@DeleteMapping("/deleteUser")
public String deleteUser(){
int i = userMapper.deleteUser(4);
if (i>0){
return "删除成功";
}else {
return "删除失败";
}
}
@PutMapping("/updateUser")
public String updateUser(){
User user = userMapper.getUserById(1);
user.setUserName("zxp");
user.setPassword("999");
user.setAge(24);
int i = userMapper.updateUser(user);
if (i>0){
return "修改成功";
}else {
return "修改失败";
}
}
}
以上工作做完后,就可以启动项目,使用接口测试工具进行测试。
2、XML配置版本
修改application.properties
在上面配置的基础上,增加下面两行
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
然后在resources下创建mybatis文件夹,在mybatis文件夹下创建mybatis-config.xml配置文件,在mybatis文件夹下继续创建mapper文件夹,在这个mapper文件夹下创建UserMapper.xml文件。这两个文件的内容分别如下:
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>
<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>
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="cn.xupengzhuang.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="cn.xupengzhuang.entity.User" >
<id column="user_id" property="userId" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<!-- 查询所有 -->
<select id="getAllUsers" resultMap="BaseResultMap" >
select * from user
</select>
<!-- 根据主键查询 -->
<select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
select * from user where user_id = #{id}
</select>
<!-- 添加 -->
<insert id="addUser" parameterType="cn.xupengzhuang.entity.User" >
insert into user values(#{userId},#{userName},#{password},#{age})
</insert>
<!-- 删除 -->
<delete id="deleteUser" parameterType="java.lang.Integer" >
delete from user where user_id = #{id}
</delete>
<!-- 修改 -->
<update id="updateUser" parameterType="cn.xupengzhuang.entity.User" >
update user set user_name=#{userName},password=#{password},age=#{age} where user_id = #{userId}
</update>
</mapper>
编写UserMapper文件
public interface UserMapper {
/**
* 查询所有
*/
List<User> getAllUsers();
/**
* 根据主键查询
*/
User getUserById(@Param("id") Integer id);
/**
* 添加
*/
int addUser(User user);
/**
* 删除
*/
int deleteUser(@Param("id") Integer id);
/**
* 修改
*/
int updateUser(User user);
}
编写完后,启动项目,然后就可以使用接口测试进行测试了。