本篇讲解springboot集成mybatis,并使用注解方式进行持久化操作
springboot集成mybatis
新建一个springboot,或者已上一篇为基础
- 在pom.xml中引入mybatis需要的依赖:mybatis-spring-boot-starter
- 在pom.xml中引入mysql需要的依赖:mysql-connector-java
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</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.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 在配置文件中配置mysql链接信息
spring.datasource.url=jdbc:mysql://localhost:3306/my?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- 新建一个用户表user,sql如下
CREATE TABLE `user` (
`id` varchar(32) NOT NULL,
`name` varchar(16) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- 新建对应的映射po类,User.java
public class User {
private String id;
private String name;
private int age;
private String address;
//省略对应get,set方法
}
- 持久化实现:新建一个UserMapper接口,用来实现对数据库进行操作
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User findUserByName(@Param("id") String id) throws Exception;
@Insert("insert into user values (#{id},#{name},#{age},#{address})")
void insert(User user);
@Update("update user set name=#{name},age=#{age},address=#{address} where id = #{id}")
void update(User user);
@Delete("delete from user where id=#{id}")
void delete(@Param("id") String id);
}
- 这里就不贴业务层的代码了,没啥业务逻辑,就是直接调用,想看的去看源码,直接贴出Controller的代码
@GetMapping("/users/{id}")
public User getUserById(@PathVariable String id) throws Exception{
return userServiceImpl.findUserByName(id);
}
@PostMapping("/users")
public String addUsers(User user) throws Exception{
userServiceImpl.insert(user);
return "模拟添加:"+user.toString();
}
@PutMapping("/users")
public String updateUserById(User user) throws Exception{
userServiceImpl.update(user);
return "模拟更新:"+user.toString();
}
@DeleteMapping("/users/{id}")
public String deleteUserById(@PathVariable String id) throws Exception{
userServiceImpl.delete(id);
return "模拟删除 :"+id;
}
- 程序入口类:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
运行程序后,依次测试接口;
你会发现其实springboot集成mybatis真的很简单
码云 :https://gitee.com/cmy1996/springboot
github :https://github.com/mingyuHub/springboot
作者:陈明羽
转载请注明出处:http://101.132.73.145/