转:http://blog.csdn.net/u013187139/article/details/68944972
在众多orm框架中,我对mybatis最熟悉,所以我采用mybatis进行整合,对我们的orm框架,这里我们也提出几点要求
在查阅了一些资料后,找到目前为止最简单的一种整合mybatis方式,这里贴出原始博客地址
http://blog.didispace.com/springbootmybatis/
参照大神的整合,我们的整合异常的顺利,贴出我们增加的代码
在pom中添加以下依赖
<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 中增加以下配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
表结构
Create Table: CREATE TABLE `userinfo` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
编写dao层代码,新建UserDao 接口
@Mapper
public interface UserDao {
@Select("SELECT * FROM USERINFO WHERE username = #{username}")
UserInfo findByName(@Param("username") String username);
@Insert("INSERT INTO USERINFO(username, password) VALUES(#{username}, #{password})")
int insert(@Param("username") String name, @Param("password") String password);
}
在业务层增加对dao层接口的引用,修改TestInterFace,TestInterFaceImpl
public interface TestInterFace {
public int testInterFace();
public UserInfo testUser();
public int insertUser(String username,String password);
}
@Service
public class TestInterFaceImpl implements TestInterFace {
@Autowired UserDao userDao;
@Override public int testInterFace() {
return 0;
}
@Override public UserInfo testUser() {
return new UserInfo();
}
@Override public int insertUser(String username,String password) {
return userDao.insert(username,password);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
接下来修改我们的controller,提供对外的接口,修改UserController
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private TestInterFace testInterFace;
@RequestMapping("/get")
@ResponseBody UserInfo getUser() {
return testInterFace.testUser();
}
@RequestMapping("/add")
@ResponseBody String add() {
testInterFace.insertUser("username123寇鑫","password123寇鑫");
return "插入成功";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
来测试一下我们的新接口,访问 http://localhost:8080/user/add
看到浏览器已经正常返回了,接下来去数据库看看数据有没有实际插入
+----+-------------------+-------------------+
可以看到,在我们的表中,已经插入了一条数据,并且中文显示正常。但现在每次新加一个接口,都要对应的写一条sql,这样很麻烦,而且不利于开发,业务方不能专注于业务的开发,所以我们要抽象出来通用的curd接口,并且支付分页。
2017-04-04
mybatis有很多成熟的分页插件以及通用接口插件,这里我们也采用目前较为成熟的方案,不必重复造轮子。
添加pom
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
因为springboot 不需要设置xml,所以这里都采用注解和代码的形式注入插件
新建配置类
package com.kx.springboot.dao.mybatis
import com.github.pagehelper.PageHelper
import org.apache.ibatis.plugin.Interceptor
import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.SqlSessionFactoryBean
import org.springframework.context.annotation.Bean
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.core.io.support.ResourcePatternResolver
import java.util.Properties
public class MyBatisConfig {
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean()
// bean.setDataSource(dataSource())
bean.setTypeAliasesPackage("com.kx.springboot.bean")
//分页插件设置
PageHelper pageHelper = new PageHelper()
Properties properties = new Properties()
properties.setProperty("reasonable", "true")
properties.setProperty("supportMethodsArguments", "true")
properties.setProperty("returnPageInfo", "check")
properties.setProperty("params", "count=countSql")
pageHelper.setProperties(properties)
//添加分页插件
bean.setPlugins(new Interceptor[]{pageHelper})
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver()
try {
//基于注解扫描Mapper,不需配置xml路径
//bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"))
return bean.getObject()
} catch (Exception e) {
e.printStackTrace()
throw new RuntimeException(e)
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
新建配置扫描类
package com.kx.springboot.dao.mybatis;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import java.util.Properties;
/**
* Created by kx on 17/4/2.
*/
@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.kx.springboot.dao.mybatis");
Properties properties = new Properties();
properties.setProperty("mappers", "com.kx.springboot.dao.baseDao.MyMapper");
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
新建对外暴露接口
package com.kx.springboot.dao.baseDao;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
现在,修改我们的dao层实现类,继承我们的通用接口
@Mapper
public interface UserDao extends MyMapper<UserInfo> {
}
在业务层中增加想要调用的方法
public interface TestInterFace {
public int testInterFace();
public UserInfo testUser();
public int insertUser(UserInfo userInfo);
List<UserInfo> selectALL();
}
@Service
public class TestInterFaceImpl implements TestInterFace {
@Autowired UserDao userDao;
@Override public int testInterFace() {
return 0;
}
@Override public UserInfo testUser() {
return new UserInfo();
}
@Override public int insertUser(UserInfo userInfo) {
return userDao.insert(userInfo);
}
@Override
public List<UserInfo> selectALL(){
return userDao.selectAll();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
看到我们在调用userDao时已经有了通用的单表查询方法。将新接口暴露给http,修改controller
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private TestInterFace testInterFace;
@RequestMapping("/get")
@ResponseBody UserInfo getUser() {
return testInterFace.testUser();
}
@RequestMapping("/add")
@ResponseBody String add() {
UserInfo user = new UserInfo();
user.setUsername("username123寇鑫");
user.setPassword("password123寇鑫");
testInterFace.insertUser(user);
return "插入成功";
}
@RequestMapping("/getall")
@ResponseBody List<UserInfo> getall() {
return testInterFace.selectALL();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
访问http://localhost:8080/user/getall
程序抛出异常
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist
### The error may exist in com/kx/springboot/dao/UserDao.java (best guess)
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: SELECT username,password FROM user_info
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'ssmtest.user_info' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
从异常可以看出来,我们的表和我们查询数据库的字段没有映射起来,查询资料后发现原因是通用插件的问题,默认的字段中有下划线,我们需要手动指定映射
修改userinfo类
package com.kx.springboot.bean;
import javax.persistence.Column;
import javax.persistence.Table;
/**
* Created by kx on 17/3/29.
*/
@Table(name = "userinfo")
public class UserInfo {
@Column(name = "username")
private String username = "username寇鑫123";
@Column(name = "password")
private String password = "password寇鑫123";
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;
}
@Override public String toString() {
return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}