Springboot+MyBatis+JPA集成

1.前言

Springboot最近可谓是非常的火,本人也在项目中尝到了甜头。之前一直使用Springboot+JPA,用了一段时间发现JPA不是太灵活,也有可能是我不精通JPA,总之为了多学学Springboot我决定尝试一下Springboot+MyBatis+JPA三项集成,集成过程中遇到了很多问题,但最后总算是集成成功了,现在记录一下方法。

1.1 如何使用MyBatis Generator自动生成xxxMapper.java接口以及xxxMapper.xml文件

以前用过SpringMVC,知道写xxxMapper.java接口以及xxxMapper.xml文件的辛苦,这次集成最先想到的就是先解决如何使用如何使用MyBatis Generator自动生成这些文件的问题。

先扔出MyBatis Generator的官网->请戳这里

我使用的Maven集成插件的方式,IDE使用的是IDEA

1.1.1 创建项目

 
20180126110629.png
 
20180126110757.png
 
20180126110812.png

1.1.2 修改pom.xml

添加了Druid依赖和MyBatis Generator插件

其他依赖请自行添加

"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.0modelVersion> <groupId>com.study.springbootgroupId> <artifactId>mybatisartifactId> <version>1.0version> <packaging>warpackaging> <name>demoname> <description>springboot+mybatis+jpadescription> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>1.5.9.RELEASEversion> <relativePath/> parent> <properties> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding> <java.version>1.8java.version> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-jpaartifactId> dependency> <dependency> <groupId>org.mybatis.spring.bootgroupId> <artifactId>mybatis-spring-boot-starterartifactId> <version>1.3.1version> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <scope>runtimescope> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-tomcatartifactId>  dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency>  <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>1.1.5version> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin>  <plugin> <groupId>org.mybatis.generatorgroupId> <artifactId>mybatis-generator-maven-pluginartifactId> <version>1.3.5version> <executions> <execution> <id>Generate MyBatis Artifactsid> <goals> <goal>generategoal> goals> execution> executions> plugin> plugins> build> project> 

1.1.3 配置generatorConfiguration

generatorConfig.xml放在resource文件夹下

常用配置已经注释了,请自行查看

"1.0" encoding="UTF-8"?>  <generatorConfiguration>    <classPathEntry location="C:\Users\Semi\.m2\repository\mysql\mysql-connector-java\5.1.38\mysql-connector-java-5.1.38.jar"/>  <context id="MyBatis" targetRuntime="MyBatis3">  <property name="autoDelimitKeywords" value="false"/>  <property name="javaFileEncoding" value="UTF-8"/>  <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>  <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>  <commentGenerator> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> commentGenerator>  <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="123456"/>  <javaTypeResolver>  <property name="forceBigDecimals" value="false"/> javaTypeResolver>  <javaModelGenerator targetPackage="com.study.springboot.mybatis.model" targetProject="E:\WorkSpace\study\springboot\mybatis\src\main\java">    <property name="enableSubPackages" value="false"/>      <property name="trimStrings" value="true"/> javaModelGenerator>  <sqlMapGenerator targetPackage="mapper" targetProject="E:\WorkSpace\study\springboot\mybatis\src\main\resources">  <property name="enableSubPackages" value="false"/> sqlMapGenerator>  <javaClientGenerator type="XMLMAPPER" targetPackage="com.study.springboot.mybatis.mapper" targetProject="E:\WorkSpace\study\springboot\mybatis\src\main\java">  <property name="enableSubPackages" value="false"/>  javaClientGenerator>  <table tableName="%" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">                                         table> context> generatorConfiguration> 

1.1.4 生成xxxMapper.java接口以及xxxMapper.xml文件

 
20180126111603.png

注意,如果存放xxxMapper.java和xxxMapper.xml文件的包不存在会报错

1.1.5 修改自动生成的实体类

对于model包下的实体类需要添加基于JPA的注解,否则JPA接口无法引用

例如对于User.java实体类需要进行如下修改


package com.study.springboot.mybatis.model;

import javax.persistence.*;

@Entity @Table(name = "user") public class User { @Id @GeneratedValue @Column(name = "id") private Integer id; @Column(name = "user_name") private String userName; @Column(name = "passwd") private String passwd; @Column(name = "nick_name") private String nickName; @Column(name = "telephone") private String telephone; @Column(name = "email") private String email; @Column(name = "authority") private Integer authority; @Column(name = "department") private String department; @Column(name = "create_at") private String createAt; @Column(name = "update_at") private String updateAt; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd == null ? null : passwd.trim(); } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName == null ? null : nickName.trim(); } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone == null ? null : telephone.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Integer getAuthority() { return authority; } public void setAuthority(Integer authority) { this.authority = authority; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department == null ? null : department.trim(); } public String getCreateAt() { return createAt; } public void setCreateAt(String createAt) { this.createAt = createAt == null ? null : createAt.trim(); } public String getUpdateAt() { return updateAt; } public void setUpdateAt(String updateAt) { this.updateAt = updateAt == null ? null : updateAt.trim(); } } 

1.1.6 添加xxxJPA接口,例如UserJPA.java


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import java.io.Serializable; public interface UserJPA extends Serializable, JpaRepository<User, Integer>, JpaSpecificationExecutor<User> { } 

1.1.7 测试

测试之前需要配置application.yml(你的有能是application.properties,改一下后缀名即可,我比较喜欢.yml文件的简洁)

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 driver-class-name: com.mysql.jdbc.Driver username: root password: 123456 mybatis: # 重要配置 type-aliases-package: com.study.springboot.mybatis.model mapper-locations: classpath:mapper/*.xml 

对于每一个xxxMapper.java接口,需要使用@Component注解

自动生成的xxxMapper.java接口是不带@Component注解的

@Component
public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); } 

在入口类中需要添加@MapperScan("com.study.springboot.mybatis.mapper")注解

@SpringBootApplication
@MapperScan("com.study.springboot.mybatis.mapper") public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } } 

打开测试类,为测试类添加@MapperScan("com.study.springboot.mybatis.mapper")注解

@RunWith(SpringRunner.class)
@SpringBootTest
@MapperScan("com.study.springboot.mybatis.mapper") public class MybatisApplicationTests { @Autowired private UserMapper userMapper; @Autowired private UserJPA userJPA; @Test public void contextLoads() { System.out.println(userMapper.selectByPrimaryKey(11).getUserName()); System.out.println(userJPA.findOne(11).getUserName()); } } 
 
20180126110153.png

最后如果出现

java.lang.NoClassDefFoundError: org/apache/ibatis/session/SqlSession

的错误,请检查本地Maven仓库的配置,有可能是没有Maven没有下载需要引用的包

---恢复内容结束---

---恢复内容结束---

你可能感兴趣的:(Springboot+MyBatis+JPA集成)