SpringBoot整合Mybatis
2018-09-23 本文已影响6人
WebGiser
SpringBoot整合Mybatis的示例,开发环境:jdk1.8,数据库:postgresql。
1、新建SpringBoot项目,工程结构如下:
image.png2、pom.xml依赖:
<?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>temp.springboot</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Mybatis-SpringBoot整合包 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- c3p0连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--PostgreSQL数据库依赖-->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<!--<version>42.2.5</version>-->
</dependency>
<!-- junit测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、application.properties:
#server配置
server.port = 8081
server.servlet.context-path = /temp
#spring.datasource.driver-class-name = org.postgresql.Driver
#spring.datasource.url = jdbc:postgresql://127.0.0.1:5432/postgres
#spring.datasource.username = postgres
#spring.datasource.password = 19920318
#数据库配置
jdbc.jdbcDriver = org.postgresql.Driver
jdbc.jdbcUrl = jdbc:postgresql://localhost:5432/postgres
jdbc.jdbcUsername = postgres
jdbc.jdbcPassword = 19920318
#Mybatis配置
mybatis_config_file = mybatis-config.xml
mapper_path = /mapper/**.xml
entity_package =temp.springboot.entity
#spring.jpa配置
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.PostgreSQL10Dialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
4、Mybatis配置
4.1、mybatis-config.xml(位于resources目录下):
<?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>
<settings>
<!--使用jdbc的useGeneratedKeys获取数据库自增主键值-->
<setting name="useGeneratedKeys" value="true"/>
<!--使用列标签代替列别名,默认:true-->
<setting name="useColumnLabel" value="true"/>
<!--开启驼峰命名转换,例如:Table{create_time} -> Entity{createTime}-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
4.2、DataSourceConfiguration.java:
package temp.springboot.config.dao;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.beans.PropertyVetoException;
@Configuration
//配置Mybatis mapper的扫描路径
@MapperScan("temp.springboot.config.dao")
public class DataSourceConfiguration {
@Value("${jdbc.jdbcDriver}")
private String jdbcDriver;
@Value("${jdbc.jdbcUrl}")
private String jdbcUrl;
@Value("${jdbc.jdbcUsername}")
private String jdbcUsername;
@Value("${jdbc.jdbcPassword}")
private String jdbcPassword;
@Bean(name = "DataSource")
public ComboPooledDataSource createDataSourceBean() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(jdbcDriver);
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setUser(jdbcUsername);
dataSource.setPassword(jdbcPassword);
//关闭连接后不自动commit
dataSource.setAutoCommitOnClose(false);
return dataSource;
}
}
4.3、SessionFactoryConfiguration.java:
package temp.springboot.config.dao;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
import java.io.IOException;
@Configuration
public class SessionFactoryConfiguration {
//mybatis-config.xml文件路径
@Value("${mybatis_config_file}")
private String mybatisConfigFilePath;
//mybatis mapper文件路径
@Value("${mapper_path}")
private String mapperPath;
//实体类所在的package路径
@Value("${entity_package}")
private String entityPackage;
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
}
4.4、GirlMapper.xml(位于resources/mapper目录下):
<?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="temp.springboot.dao.GirlDao">
<insert id="insertGirl" useGeneratedKeys="true" keyProperty="id"
keyColumn="id" parameterType="temp.springboot.entity.Girl">
insert into girl(id,age,name) values(nextval('girl_id_sequence'),#{age},#{name})
</insert>
<delete id="deleteGirlById">
delete from girl where id= #{id}
</delete>
<update id="updateGirl">
update girl
<set>
<if test="age != null">age = #{age},</if>
<if test="name != null">name = #{name}</if>
</set>
where id = #{id}
</update>
<select id="selectGirlById" resultType="temp.springboot.entity.Girl">
select id,age,name from girl where id = #{id}
</select>
<select id="selectAllGirl" resultType="temp.springboot.entity.Girl">
select id,age,name from girl
</select>
</mapper>
5、entity实体层:Girl.java
package temp.springboot.entity;
public class Girl {
private int id;
private String name;
private int age;
public Girl(){
}
@Override
public String toString() {
return "Girl{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
6、dao层:GirlDao
package temp.springboot.dao;
import org.apache.ibatis.annotations.Mapper;
import temp.springboot.entity.Girl;
import java.util.List;
@Mapper
public interface GirlDao{
int insertGirl(Girl girl);
void deleteGirlById(int id);
void updateGirl(Girl girl);
Girl selectGirlById(int id);
List<Girl> selectAllGirl();
}
7、service层
7.1、service:GirlService.java:
package temp.springboot.service;
import temp.springboot.entity.Girl;
import java.util.List;
public interface GirlService {
int insertGirl(Girl girl);
Boolean deleteGirlById(int id);
Boolean updateGirl(Girl girl);
Girl selectGirlById(int id);
List<Girl> selectAllGirl();
}
7.2、GirlServiceImpl.java:
package temp.springboot.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import temp.springboot.dao.GirlDao;
import temp.springboot.entity.Girl;
import temp.springboot.service.GirlService;
import java.util.List;
@Service
public class GirlServiceImpl implements GirlService {
@Autowired
private GirlDao girlDao;
@Transactional
@Override
public int insertGirl(Girl girl) {
return girlDao.insertGirl(girl);
}
@Transactional
@Override
public Boolean deleteGirlById(int id) {
if(id > 0){
girlDao.deleteGirlById(id);
return true;
}else{
throw new RuntimeException("删除对象时,对象id应该大于0!");
}
}
@Transactional
@Override
public Boolean updateGirl(Girl girl) {
if(new Integer(girl.getId()) != null){
girlDao.updateGirl(girl);
return true;
}else{
throw new RuntimeException("更新对象时,对象id不能为空!");
}
}
@Override
public Girl selectGirlById(int id) {
if(id > 0){
return girlDao.selectGirlById(id);
}else{
throw new RuntimeException("查询对象时,对象id应该大于0!");
}
}
@Override
public List<Girl> selectAllGirl() {
return girlDao.selectAllGirl();
}
}
8、Controller层:GirlController.java
package temp.springboot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import temp.springboot.entity.Girl;
import temp.springboot.service.GirlService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/girl")
public class GirlController {
@Autowired
private GirlService girlService;
@RequestMapping(value = "/add",method = RequestMethod.POST)
public Map<String,Object> insertGirl(@RequestBody Girl girl){
Map<String,Object> map = new HashMap<String,Object>();
girlService.insertGirl(girl);
map.put("status","success");
return map;
}
@RequestMapping(value = "/delete",method = RequestMethod.GET)
public Map<String,Object> deleteGirlById(int id){
Map<String,Object> map = new HashMap<String,Object>();
girlService.deleteGirlById(id);
map.put("status","success");
return map;
}
@RequestMapping(value = "/update",method = RequestMethod.POST)
public Map<String,Object> updateGirl(@RequestBody Girl girl){
Map<String,Object> map = new HashMap<String,Object>();
girlService.updateGirl(girl);
map.put("status","success");
return map;
}
@RequestMapping(value = "/select",method = RequestMethod.GET)
public Map<String,Object> selectGirlById(int id){
Map<String,Object> map = new HashMap<String,Object>();
Girl girl = girlService.selectGirlById(id);
map.put("status","success");
map.put("data",girl);
return map;
}
@RequestMapping(value = "/all",method = RequestMethod.GET)
public Map<String,Object> selectAllGirl(){
Map<String,Object> map = new HashMap<String,Object>();
List<Girl> list = girlService.selectAllGirl();
map.put("status","success");
map.put("data",list);
return map;
}
}
9、功能测试(使用IDEA软件Tools下的Test RESRful Web Service进行功能测试)
增加一条数据:
add.png
删除一条数据:
delete.png
修改一条数据:
update.png
查询一条数据:
select.png
查询所有数据:
all.png