GitHub 地址:
https://github.com/asd821300801/Spring-Boot.git
集成Mybatis的两种方式
前期准备
- SQL语句
sql文件存放在:src\test\resources\user.sql
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`account` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `aaabb` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('72', '超级管理员', 'admin');
- pom.xml文件中添加mybatis相关依赖
<!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
- 在启动类中添加对mapper包扫描@MapperScan
@MapperScan("com.example.mapper")
//启动时默认不连接数据库
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
- 添加数据源
//DataSource配置
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
//提供SqlSeesion
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
- SpringbootHelloApplication.java 完整源码
package com;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.web.servlet.DispatcherServlet;
import com.example.servlet.Servlet1;
/**
* Spring Boot 教程一
* Spring Boot 入门
* @author LingDu
*/
//@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}) 启动时不使用数据库
@SpringBootApplication
@ServletComponentScan //使用注解的方式注册servlet需要在SpringbootHelloApplication.java中添加@ServletComponentScan注解
@ComponentScan
@MapperScan("com.example.mapper")//扫描com.example.mapper包下的类
public class SpringbootHelloApplication {
/*@Bean
public ServletRegistrationBean servletRegistrationBean() {
return new ServletRegistrationBean(new Servlet1(),"/servlet/*");// ServletName默认值为首字母小写,即servlet
}*/
/**
* 修改DispatcherServlet默认配置
*
* @param dispatcherServlet2
* @author LingDu
*/
@Bean
public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
ServletRegistrationBean registration = new ServletRegistrationBean(dispatcherServlet);
registration.getUrlMappings().clear();
registration.addUrlMappings("*.action"); //只有*.action 的请求能通过
registration.addUrlMappings("*.json");
return registration;
}
//DataSource配置
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
//提供SqlSeesion
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));//映射文件是resource/mybatis/目录下所有.xml文件
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
public static void main(String[] args) {
SpringApplication.run(SpringbootHelloApplication.class, args);
}
}
- 配置文件中添加数据库信息
application.properties 添加相关配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/lingdu?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中
- 创建domain类User.java
包所在: com.example.domain
package com.example.domain;
/**
* domain层
* @author LingDu
*
*/
public class User {
private int id;
private String name;
private String account;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", account=" + account + "]";
}
}
xml配置文件的方式集成Mybatis
- 创建UserMapper接口
包所在: com.example.mapper
package com.example.mapper;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import com.example.domain.User;
/**
* dao层
* 对应User表
* @author LingDu
*/
public interface UserMapper {
public List<User> list();
public User get(Integer id);
public void add(User user);
public void update(User user);
public void delete(Integer id);
}
- 资源目录添加XML映射文件
文件路径:src/main/resources/mybatis/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.mapper.UserMapper" ><!-- 命名空间必须指定mapper类的全路径 -->
<!-- id必须与mapper接口方法名一致,不能出现重载 -->
<select id="get" parameterType="int" resultType="com.example.domain.User">
select id,name,account from user where id=#{id}
</select>
<select id="list" resultType="com.example.domain.User">
select id,name,account from user
</select>
<insert id="add" parameterType="com.example.domain.User" useGeneratedKeys="true" keyProperty="id">
<!--
useGeneratedKeys="true" keyProperty="id" 添加之后返回自增的ID
-->
insert into user(id,name,account) values(#{id},#{name},#{account})
</insert>
<update id="update" parameterType="com.example.domain.User">
UPDATE user SET name=#{name} WHERE id=#{id}
</update>
<delete id="delete" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>
- 创建Server层
包所在:com.example.service
UserService 接口
package com.example.service;
import java.util.List;
import com.example.domain.User;
public interface UserService {
public List<User> getAll();
public User getUser(Integer id);
public void insert(User user);
public void update(User user);
public void delete(Integer id);
}
UserServiceImp 实现类
package com.example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.domain.User;
import com.example.mapper.UserMapper;
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserMapper mapper;
@Override
public List<User> getAll() {
return mapper.list();
}
@Override
public User getUser(Integer id) {
return mapper.get(id);
}
@Override
public void insert(User user) {
mapper.add(user);
}
@Override
public void update(User user) {
mapper.update(user);
}
@Override
public void delete(Integer id) {
mapper.delete(id);
}
}
- 创建Controller类
包所在:com.example.controller
package com.example.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.domain.User;
import com.example.service.UserService;
@RestController
@RequestMapping("/user")
public class UserController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserService service;
@RequestMapping("/all")
public List<User> getUser(){
List<User> list = service.getAll();
logger.info(list.toString());
return list;
}
}
- 测试
注解的方式集成Mybatis
上面已经介绍了如何使用xml的方式集成Mybatis,下面来试试纯注解的方式集成Mybatis
1、pom.xml添加依赖
2、在启动类中添加对mapper包扫描@MapperScan
3、application.properties 添加相关配置
- 创建Mapper接口
为了区分,我将类名命名为:UserAnnotateMapper
包所在: com.example.mapper
package com.example.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.domain.User;
/**
* dao层
* 对应User表
* @author LingDu
*/
public interface UserAnnotateMapper {
@Select("SELECT * FROM USER")
@Results({
@Result(property="id",column="id",javaType=Integer.class),
@Result(property="name",column="name"),
@Result(property="account",column="account")
})
public List<User> list();
@Select("SELECT * FROM USER WHERE ID = #{id}")
@Results({
@Result(property="id",column="id",javaType=Integer.class),
@Result(property="name",column="name"),
@Result(property="account",column="account")
})
public User get(Integer id);
@Insert("INSERT INTO USER(NAME,ACCOUNT) VALUES(#{name},#{account})")
public void add(User user);
@Update("UPDATE USER SET NAME=#{name},ACCOUNT=#{account} WHERE id=#{id}")
public void update(User user);
@Delete("DELETE FROM USER WHERE ID = #{id}")
public void delete(Integer id);
}
- 创建Service层
跟上面的Service一样,这里就不贴代码了。
- 创建测试类
完整测试代码
package com.example.test;
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.domain.User;
import com.example.service.UserService;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserAnnotateMapperTest {
@Autowired
private UserService service;
@Test //在需要运行的方法上添加 @Test 注解即可运行
public void getAll() throws Exception {
System.out.println(service.getAll());
}
//@Test
public void add() throws Exception {
User user = new User();
user.setName("lingdu");
user.setAccount("lingdu");
service.insert(user);
}
//@Test
public void update() throws Exception {
User user = new User();
//更新id=76的用户
user.setId(79);
//更新后的值
user.setName("admin_lingdu");
user.setAccount("admin_lingdu");
service.update(user);
}
//@Test
public void delete() throws Exception {
service.delete(79);
}
//@Test
public void getUser() throws Exception {
System.out.println(service.getUser(79));
}
}
- 单个方法进行测试的结果如下:
/@Test
public void add() throws Exception {
User user = new User();
user.setName("lingdu");
user.setAccount("lingdu");
service.insert(user);
}
@Test
public void getUser() throws Exception {
System.out.println(service.getUser(79));
}
@Test
public void update() throws Exception {
User user = new User();
//更新id=76的用户
user.setId(79);
//更新后的值
user.setName("admin_lingdu");
user.setAccount("admin_lingdu");
service.update(user);
}
@Test
public void getAll() throws Exception {
System.out.println(service.getAll());
}
@Test
public void delete() throws Exception {
service.delete(79);
}
工程结构图
总结
- 两种模式各有特点,注解版适合简单快速的模式,其实像现在流行的这种微服务模式,一个微服务就会对应一个自已
的数据库,多表连接查询的需求会大大的降低,会越来越适合这种模式。
- 老传统模式比适合大型项目,可以灵活的动态生成SQL,方便调整SQL,也有痛痛快快,洋洋洒洒的写SQL的感觉。