SpringBoot整合JpaMapper实现基于mybatis
SpringBoot整合JpaMapper实现基于mybatis的快速开发
官方主页
概述
Jpa-Mapper是一款基于Mybatis的快速开发工具,能将jpa-hibernate的书写风格基于mybatis实现,同时保留mybatis的特性。基于Jpa-Mapper,我们可以使用mybatis的同时,方便快捷地生成我们的CRUD代码。
本篇主要介绍SpringBoot基于Jpa-Mapper实现CRUD功能。
开始搭建
pom.xml文件
首先引入maven的依赖jar包
<?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>
<artifactId>spring-boot-example</artifactId>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
</parent>
<name>spring-boot-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mybatis.version>3.4.6</mybatis.version>
<mybatis-spring.version>1.3.2</mybatis-spring.version>
<mybatis-spring-boot.version>1.3.0</mybatis-spring-boot.version>
<jpa.version>1.0</jpa.version>
<jpa-mapper.version>2.0</jpa-mapper.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>cn.pomit</groupId>
<artifactId>jpa-mapper-spring-boot-starter</artifactId>
<version>${jpa-mapper.version}</version>
</dependency>
<!--必须依赖-->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SpringBoot配置文件application.properties
server.port=8080
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/feiyun?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=cff
spring.datasource.password=123456
spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.dbcp2.max-wait-millis=60000
spring.datasource.dbcp2.min-idle=20
spring.datasource.dbcp2.initial-size=2
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.connection-properties=characterEncoding=utf8
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.test-on-borrow=true
spring.datasource.dbcp2.test-on-return=false
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
SpringBoot启动文件
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
到这里,SpringBoot的环境已经建好了,下面可以引入JpaMapper了。
JpaMapper引入
建表sql
首先建好表,如建表语句为:
CREATE TABLE `f_personal_info` (
`domain` varchar(16) NOT NULL DEFAULT '',
`user_name` varchar(64) DEFAULT NULL,
`real_name` varchar(64) DEFAULT NULL,
`mobile` varchar(13) DEFAULT NULL,
`web_name` varchar(100) DEFAULT NULL,
`email` varchar(64) DEFAULT NULL,
`content` text,
`file_id` bigint(20) DEFAULT NULL,
`status` int(4) DEFAULT NULL COMMENT '0:通过 1:待审核 2:拒绝',
`edit_type` int(1) unsigned zerofill DEFAULT NULL COMMENT '0:文件修改 1:文件无修改',
`create_time` datetime DEFAULT NULL,
PRIMARY KEY (`domain`)
)
建表语句可以直接从navcat复制。
生成实体
生成实体domain。(可以在网站https://www.pomit.cn/java/java/sqlToSpringboot.html一站式生成实体、DAO、Service、Controller)
在网站上生成的实体是Jpa-hibernate的实体,我们需要做下简单调整,将所有映射到数据库的实体都要加上@Column。
实体PersonalInfo:
import javax.persistence.Table;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Id;
@Table(name = "f_personal_info")
public class PersonalInfo {
@Id
@Column()
private String domain;
@Column(name = "user_name")
private String userName;
@Column(name = "real_name")
private String realName;
@Column()
private String mobile;
@Column(name = "web_name")
private String webName;
@Column()
private String email;
@Column()
private String content;
@Column(name = "file_id")
private long fileId;
@Column(name = "edit_type")
private long editType;
private String webUrl;
@Column()
private Integer status;
@Column(name = "create_time")
private Date createTime;
public void setDomain(String domain) {
this.domain = domain;
}
public String getDomain() {
return domain;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getRealName() {
return realName;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMobile() {
return mobile;
}
public void setWebName(String webName) {
this.webName = webName;
}
public String getWebName() {
return webName;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setFileId(long fileId) {
this.fileId = fileId;
}
public long getFileId() {
return fileId;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getWebUrl() {
return webUrl;
}
public void setWebUrl(String webUrl) {
this.webUrl = webUrl;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public long getEditType() {
return editType;
}
public void setEditType(long editType) {
this.editType = editType;
}
}
生成DAO
生成Dao(或者说Mapper)。(可以在网站https://www.pomit.cn/java/java/sqlToSpringboot.html一站式生成实体、DAO、Service、Controller)
在网站上生成的Dao是Jpa-hibernate的Dao,我们需要做下简单调整,直接将CrudRepository改为CrudMapper即可,另外加上注解@Mapper。
如,PersonalInfoDao:
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.cff.feiyun.api.domain.PersonalInfo;
import cn.pomit.jpamapper.core.mapper.CrudMapper;
@Mapper
public interface PersonalInfoDao extends CrudMapper<PersonalInfo, String> {
List<PersonalInfo> findByStatus(int status);
@Select({
"<script>",
"select domain domain,real_name realName,create_time createTime,web_name webName,mobile mobile,user_name userName,email email,content content,file_id fileId,status status",
"FROM f_personal_info where user_name = #{userName, jdbcType=VARCHAR}",
"order by create_time desc limit 1",
"</script>"})
public PersonalInfo findByUserNameNewest(@Param("userName") String userName);
}
生成Service
生成Service。(可以在网站https://www.pomit.cn/java/java/sqlToSpringboot.html一站式生成实体、DAO、Service、Controller)
如,PersonalInfoService:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cff.feiyun.api.dao.PersonalInfoDao;
import com.cff.feiyun.api.domain.PersonalInfo;
@Service
public class PersonalInfoService {
@Autowired
PersonalInfoDao personalInfoDao;
public void save(PersonalInfo personalInfo) {
personalInfoDao.save(personalInfo);
}
public void delete(PersonalInfo personalInfo) {
personalInfoDao.deleteEntity(personalInfo);
}
public void update(PersonalInfo personalInfo) {
personalInfoDao.update(personalInfo);
}
public List<PersonalInfo> findAll() {
return (List<PersonalInfo>) personalInfoDao.findAll();
}
public PersonalInfo findById(String id) {
return personalInfoDao.findOne(id);
}
}
生成Controller
生成Controller。(可以在网站https://www.pomit.cn/java/java/sqlToSpringboot.html一站式生成实体、DAO、Service、Controller)
如,PersonalInfoWeb:
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.cff.feiyun.api.domain.PersonalInfo;
import com.cff.feiyun.api.dto.ResultModel;
import com.cff.feiyun.api.service.PersonalInfoService;
@RestController
@RequestMapping("/personalInfo")
public class PersonalInfoWeb {
@Autowired
PersonalInfoService fPersonalInfoService;
@RequestMapping(value = "/add", method = { RequestMethod.POST })
public ResultModel add(@RequestBody PersonalInfo fPersonalInfo) {
fPersonalInfoService.save(fPersonalInfo);
return ResultModel.ok();
}
@RequestMapping(value = "/delete", method = { RequestMethod.POST })
public ResultModel delete(@RequestBody PersonalInfo fPersonalInfo) {
fPersonalInfoService.delete(fPersonalInfo);
return ResultModel.ok();
}
@RequestMapping(value = "/update", method = { RequestMethod.POST })
public ResultModel update(@RequestBody PersonalInfo fPersonalInfo) {
fPersonalInfoService.save(fPersonalInfo);
return ResultModel.ok();
}
@RequestMapping(value = "/getAll", method = { RequestMethod.GET })
public ResultModel getAll() {
return ResultModel.ok(fPersonalInfoService.findAll());
}
@RequestMapping(value = "/getOne", method = { RequestMethod.GET })
public ResultModel getOne(@RequestParam("id") String id) {
return ResultModel.ok(fPersonalInfoService.findById(id));
}
}
/**
* @author cff
*/
public class ResultModel {
private int code;
private String msg;
private Object data;
public ResultModel(){
}
public ResultModel(int code, String msg) {
this.code = code;
this.msg = msg;
}
public ResultModel(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public int getcode() {
return code;
}
public void setcode(int code) {
this.code = code;
}
public String getmsg() {
return msg;
}
public void setmsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static ResultModel ok() {
return new ResultModel(0,'成功');
}
public static ResultModel ok(Object data) {
return new ResultModel(0,'成功', data);
}
public static ResultModel error() {
return new ResultModel(1,'失败');
}
public static ResultModel error(String msg) {
return new ResultModel(1, msg);
}
}
至此SpringBoot和JpaMppaer整合可以正常使用了。