Spring boot 官网并没有提供集成Mybatis示例,CSND上还是有很多相关技术文章,都可借鉴,下面是我自己写的集成,可做参考。
pom.xml添加mybatis和数据连接池相关依赖,个人习惯使用C0P3连接池
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vic</groupId>
<artifactId>vic</artifactId>
<version>0.1.0</version>
<properties>
<java.version>1.7</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.8.RELEASE</version>
</parent>
<dependencies>
<!-- spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
项目结构如下:
application.properties文件:
#datasource
spring.datasource.jdbcUrl=jdbc:mysql://115.28.92.178:3306/wms?useUnicode\=true&characterEncoding\=utf8;autoReconnect\=true;maxReconnects\=10;connectTimeout\=180000;socketTimeout\=180000
spring.datasource.user=root
spring.datasource.password=xxx
spring.datasource.driverClass=com.mysql.jdbc.Driver
spring.datasource.maxActive=100
spring.datasource.initialPoolSize=5
spring.datasource.minPoolSize=5
spring.datasource.maxPoolSize=20
spring.datasource.maxStatements=100
spring.datasource.maxIdleTime=3600
spring.datasource.acquireIncrement=2
spring.datasource.acquireRetryAttempts=10
spring.datasource.acquireRetryDelay=600
spring.datasource.testConnectionOnCheckin=true
spring.datasource.idleConnectionTestPeriod=1200
spring.datasource.checkoutTimeout=100000
数据库(MySQL):
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT "用户ID",
`userName` varchar(30) NOT NULL UNIQUE COMMENT "用户名",
`password` VARCHAR(64) NOT NULL COMMENT "密码",
`name` varchar(30) NOT NULL COMMENT "真实姓名",
`sex` int DEFAULT 0 COMMENT "性别",
`tel` varchar(13) DEFAULT NULL COMMENT "电话",
`status` INT DEFAULT 0 COMMENT "状态",
`enable` TINYINT(1) DEFAULT 1 COMMENT "是否启用",
`createdTime` datetime not null COMMENT "创建时间",
`desc` varchar(100) DEFAULT null COMMENT "备注"
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `user` COMMENT='用户表';
INSERT INTO `USER` VALUES(1,'admin','admin','vic',1,'18700000000',0,1,now(),'system manager');
对应实体类User:
package com.vic.entity;
import java.util.Date;
/**
*
* @author vic
* @desc entity for table(user)
*
*/
public class User {
private int userId;
private String userName;
private String password;
private String name;
private int sex;
private String tel;
private int status;
private boolean enable;
private Date createdTime;
private String desc;
//getter setter ....
}
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 type="com.vic.entity.User" alias="User"/>
</typeAliases>
</configuration>
DataSourceConfig.java:
package com.vic.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
*
* @author vic
* @desc datasrouce config and mybatis scan config
*
*/
@Configuration
@EnableAutoConfiguration
@MapperScan("com.vic.dao")
public class DataSourceConfig {
private static Logger logger = Logger.getLogger(DataSourceConfig.class);
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public ComboPooledDataSource dataSource() {
return new ComboPooledDataSource();
}
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
ComboPooledDataSource dataSource = dataSource();
sqlSessionFactoryBean.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setConfigLocation(resolver.getResource("classpath:/mybatis-config.xml"));
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
logger.info("SqlSessionFactory bean init success.");
return sqlSessionFactoryBean.getObject();
}
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
}
IUserDao和UserMapper.xml
package com.vic.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.vic.entity.User;
/**
*
* @author vic
* @desc User Mapper Dao
*/
@Repository
public interface IUserDao {
public List<User> getAll();
}
<?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.vic.dao.IUserDao">
<resultMap type="User" id="UserResultMap">
<id property="userId" column="userId"/>
<result property="userName" column="userName"/>
<result property="password" column="password"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="tel" column="tel"/>
<result property="status" column="status"/>
<result property="enable" column="enable"/>
<result property="createdTime" column="createdTime"/>
<result property="desc" column="desc"/>
</resultMap>
<select id="getAll" resultMap="UserResultMap">
select * from `user`;
</select>
</mapper>
测试Controller,ResponseModal:
package com.vic.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.vic.entity.User;
import com.vic.modal.ResponseModal;
import com.vic.service.IUserService;
@RestController
public class ExampleController {
@Autowired
private IUserService userService;
@RequestMapping("/users")
public ResponseModal users(){
List<User> users = userService.getAll();
ResponseModal modal = new ResponseModal(200,true,"",users);
return modal;
}
}
package com.vic.modal;
public class Modal {
public Modal() {
super();
}
public Modal(int code, boolean success, String message) {
super();
this.code = code;
this.success = success;
this.message = message;
}
private int code;
private boolean success;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.vic.modal;
import java.io.Serializable;
public class ResponseModal extends Modal implements Serializable{
private static final long serialVersionUID = 1L;
public ResponseModal(){
super();
}
public ResponseModal(int code,boolean success,String message){
super(code,success,message);
}
public ResponseModal(int code,boolean success,String message,Object obj){
super(code,success,message);
this.response = obj;
}
private Object response;
public Object getResponse() {
return response;
}
public void setResponse(Object response) {
this.response = response;
}
}
Application.java
package com.vic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(Application.class);
application.run(args);
}
}
运行main,浏览器输入localhost:8080/users