SpringBoot整合ORM开发框架MyBatis和JPA
1、在使用Spring整合ORM组件的过程中,为了达到简化的目的,往往会进行大量的配置。利用SpringBoot可以进一步实现配置的简化。SpringBoot整合MyBatis开发框架,MyBatis是一款常用并且配置极为简单的ORM开发框架。其与Spring结合后,可以利用Spring的特征实现DAO接口的自动配置。在SpringBoot中,又对MyBatis框架的整合进行了进一步简化。
修改pom.xml配置文件,在项目中引入mybatis-spring-boot- starter依赖支持库,切记也需要数据库链接池的支持的哦。 1 <?xml version="1.0" encoding="UTF-8"?> 2 6 7 4.0.0 8 9 10 org.springframework.boot 11 spring-boot-starter-parent 12 2.3.4.RELEASE 13 14 15 16 com.bie 17 springboot-01 18 0.0.1-SNAPSHOT 19 springboot-01 20 Demo project for Spring Boot 21 22 23 1.8 24 3.1.1 25 26 27 28 29 org.springframework.boot 30 spring-boot-starter-web 31 32 33 34 org.springframework.boot 35 spring-boot-starter-test 36 test 37 38 39 org.junit.vintage 40 junit-vintage-engine 41 42 43 44 45 46 mysql 47 mysql-connector-java 48 49 50 51 org.springframework.boot 52 spring-boot-configuration-processor 53 true 54 55 56 57 58 com.alibaba 59 druid 60 1.1.9 61 62 63 64 org.mybatis.spring.boot 65 mybatis-spring-boot-starter 66 1.3.1 67 68 69 70 org.mybatis 71 mybatis 72 3.4.6 73 74 75 76 org.mybatis.spring.boot 77 mybatis-spring-boot-starter 78 2.1.1 79 80 81 org.springframework.boot 82 spring-boot-starter-jdbc 83 84 85 86 87 88 89 org.springframework.boot 90 spring-boot-maven-plugin 91 92 93 94 95
数据表结构,如下所示:
注意:如果数据表字段两个英文单词之间是下划线连接的,但是你的实体类是驼峰命名法,此时就需要进行配置,数据库字段是你下划线分隔,但是bean中的字段是驼峰命名的,如user_name和userName,导致无法匹配。如果是通过xml文件来配置的话,只需要开启驼峰命名转换,setting name="mapUnderscoreToCamelCase" value="true"/>,在/src/main/resources/mybatis/mybatis.cfg.xml里面配置即可。 1 /* 2 Navicat Premium Data Transfer 3 4 Source Server : localhost 5 Source Server Type : MySQL 6 Source Server Version : 50724 7 Source Host : localhost:3306 8 Source Schema : biehl 9 10 Target Server Type : MySQL 11 Target Server Version : 50724 12 File Encoding : 65001 13 14 Date: 15/11/2020 13:34:52 15 */ 16 17 SET NAMES utf8mb4; 18 SET FOREIGN_KEY_CHECKS = 0; 19 20 -- ---------------------------- 21 -- Table structure for user_info 22 -- ---------------------------- 23 DROP TABLE IF EXISTS `user_info`; 24 CREATE TABLE `user_info` ( 25 `user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT "用户编号", 26 `user_account` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT "用户账号", 27 `user_pw` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT "用户密码", 28 `user_number` varchar(15) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT "用户手机号", 29 `user_name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT "用户姓名", 30 `user_age` int(11) DEFAULT NULL COMMENT "用户年龄", 31 `user_sex` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT "用户性别", 32 `user_mark` varchar(5) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT "用户标志", 33 `create_time` datetime(0) DEFAULT CURRENT_TIMESTAMP COMMENT "用户创建时间", 34 `is_sync` int(3) DEFAULT 0 COMMENT "用户标识", 35 `is_money` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT "是否缴纳押金", 36 PRIMARY KEY (`user_id`) USING BTREE, 37 INDEX `user_id`(`user_id`) USING BTREE 38 ) ENGINE = InnoDB AUTO_INCREMENT = 42 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = "用户信息表" ROW_FORMAT = Dynamic; 39 40 SET FOREIGN_KEY_CHECKS = 1;
创建一个po实体类,方便数据传输,如下所示: 1 package com.bie.po; 2 3 public class UserInfo { 4 5 private Integer userId;// 用户编号 6 private String userAccount;// 用户账号 7 private String userPw;// 用户密码 8 private String userNumber;// 用户学号 9 private String userName;// 用户姓名 10 private Integer userAge;// 用户年龄 11 private String userSex;// 用户性别 12 private String userMark;// 用户标识,可以使用一张表,完成管理员和用户 13 14 private String isMoney; 15 16 public Integer getUserId() { 17 return userId; 18 } 19 20 public void setUserId(Integer userId) { 21 this.userId = userId; 22 } 23 24 public String getUserAccount() { 25 return userAccount; 26 } 27 28 public void setUserAccount(String userAccount) { 29 this.userAccount = userAccount; 30 } 31 32 public String getUserPw() { 33 return userPw; 34 } 35 36 public void setUserPw(String userPw) { 37 this.userPw = userPw; 38 } 39 40 public String getUserNumber() { 41 return userNumber; 42 } 43 44 public void setUserNumber(String userNumber) { 45 this.userNumber = userNumber; 46 } 47 48 public String getUserName() { 49 return userName; 50 } 51 52 public void setUserName(String userName) { 53 this.userName = userName; 54 } 55 56 public Integer getUserAge() { 57 return userAge; 58 } 59 60 public void setUserAge(Integer userAge) { 61 this.userAge = userAge; 62 } 63 64 public String getUserSex() { 65 return userSex; 66 } 67 68 public void setUserSex(String userSex) { 69 this.userSex = userSex; 70 } 71 72 public String getUserMark() { 73 return userMark; 74 } 75 76 public void setUserMark(String userMark) { 77 this.userMark = userMark; 78 } 79 80 public String getIsMoney() { 81 return isMoney; 82 } 83 84 public void setIsMoney(String isMoney) { 85 this.isMoney = isMoney; 86 } 87 88 @Override 89 public String toString() { 90 return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw + ", userNumber=" 91 + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex 92 + ", userMark=" + userMark + ", isMoney=" + isMoney + "]"; 93 } 94 95 }
在src/main/resources目录中创建mybatis/mybatis.cfg.xml配置文件。如果要开启驼峰命名转换,在这里开启即可,如下所示:
如果在application.properties中开启转换的话,使用mybatis.configuration.map-underscore-to-camel-case=true配置即可。 1 <?xml version="1.0" encoding="UTF-8" ?> 2 4 5 6 7 8 9 10 11 12
或者搞个配置类,如果数据库表字段Column无法自动映射到相对应的实体类属性上,我们可以在config包下新建一个自动配置类MybatisConfig,开始驼峰命名规则。
MyBatis配置文件开启驼峰命名映射 1 package com.bie.config; 2 3 import org.apache.ibatis.session.Configuration; 4 import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer; 5 import org.springframework.context.annotation.Bean; 6 7 8 @Configuration 9 public class MybatisConfig { 10 11 //注册到容器中 12 @Bean 13 public ConfigurationCustomizer configurationCustomizer(){ 14 return new ConfigurationCustomizer(){ 15 @Override 16 public void customize(Configuration configuration) { 17 //开启驼峰命名规则,是否启用下划线与驼峰式命名规则的映射 18 configuration.setMapUnderscoreToCamelCase(true); 19 20 } 21 }; 22 } 23 }
修改application.yml配置文件,追加MyBatis配置,如下所示: 1 # 配置当前要使用的数据源的操作类型 2 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 3 # 配置Mysql的驱动程序类 4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 5 # 数据库连接地址 6 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/biehl?characterEncoding=UTF-8&serverTimezone=UTC 7 # 数据库用户名称 8 spring.datasource.username=root 9 # 数据库密码 10 spring.datasource.password=123456 11 # 进行数据库链接池的配置,数据库最小维持连接数 12 spring.datasource.dbcp2.min-idle=1 13 # 数据库初始化提供的连接数 14 spring.datasource.dbcp2.initial-size=1 15 # 数据库最大维持连接数 16 spring.datasource.dbcp2.max-total=100 17 # 等待连接获取的最大超时时间 18 spring.datasource.dbcp2.max-wait-millis=3000 19 20 21 # 后台打印sql语句 22 # mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 23 # 指定sql映射文件位置,mapper下的所有.xml文件都是映射文件 24 # mybatis.mapper-locations=classpath:mapper/*Mapper.xml 25 # Mybatis配置文件所在的路径 26 mybatis.config-location=classpath:mybatis/mybatis.cfg.xml 27 # 定义所有操作类的别名所在包 28 mybatis.type-aliases-package=com.bie.po
搞几个Dao层、Service层、Controller层的接口或者类,如下所示:
注意:如果不想每次都在mapper接口上添加@Mapper注解,可以在主启动类上通过添加@MapperScan注解来批量扫描指定包下的所有mapper接口。 1 package com.bie.dao; 2 3 import java.util.List; 4 5 import org.apache.ibatis.annotations.Mapper; 6 import org.apache.ibatis.annotations.Select; 7 8 import com.bie.po.UserInfo; 9 10 @Mapper // 需要引入Mybatis的依赖包 11 public interface UserInfoDao { 12 13 /** 14 * 查询全部用户信息 15 * 16 * @return 17 */ 18 @Select(value = " select * from user_info ") 19 public List findAll(); // 查询全部用户信息 20 21 }
Service层的接口和实现类代码,如下所示: 1 package com.bie.service; 2 3 import java.util.List; 4 5 import com.bie.po.UserInfo; 6 7 public interface UserInfoService { 8 9 public List findAll(); 10 } 1 package com.bie.service.impl; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 8 import com.bie.dao.UserInfoDao; 9 import com.bie.po.UserInfo; 10 import com.bie.service.UserInfoService; 11 12 @Service 13 public class UserInfoServiceImpl implements UserInfoService { 14 15 @Autowired 16 private UserInfoDao userInfoDao; 17 18 @Override 19 public List findAll() { 20 return this.userInfoDao.findAll(); 21 } 22 23 }
控制层的代码,如下所示: 1 package com.bie.controller; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.ResponseBody; 9 10 import com.bie.po.UserInfo; 11 import com.bie.service.UserInfoService; 12 13 @Controller 14 public class UserInfoController { 15 16 @Autowired 17 private UserInfoService userInfoService; 18 19 @RequestMapping(value = "findAll") 20 @ResponseBody 21 public List findAll() { 22 List findAll = this.userInfoService.findAll(); 23 return findAll; 24 } 25 26 }
项目启动类,如下所示: 1 package com.bie; 2 3 import org.mybatis.spring.annotation.MapperScan; 4 import org.springframework.boot.SpringApplication; 5 import org.springframework.boot.autoconfigure.SpringBootApplication; 6 7 @SpringBootApplication 8 @MapperScan(value = "com.bie.dao") 9 public class Springboot01Application { 10 11 public static void main(String[] args) { 12 SpringApplication.run(Springboot01Application.class, args); 13 } 14 15 }
通过Postman测试一下,自己写的接口,看看好使不,如下所示:
项目结构,如下所示:
2、JPA是官方推出的Java持久层操作标准(现主要使用Hibernate实现),使用SpringData技术和JpaRepository接口技术,也可以达到简化数据层的目的。要在SpringBoot中使用SpringDataJPA,需要spring-boot-starter-data-jpa依赖库的支持。
修改pom.xml配置文件,引入相关依赖包,如下所示: 1 <?xml version="1.0" encoding="UTF-8"?> 2 6 4.0.0 7 8 org.springframework.boot 9 spring-boot-starter-parent 10 2.3.5.RELEASE 11 12 13 com.example 14 demo 15 0.0.1-SNAPSHOT 16 demo 17 Demo project for Spring Boot 18 19 20 1.8 21 3.1.1 22 23 24 25 26 org.springframework.boot 27 spring-boot-starter-web 28 29 30 31 org.springframework.boot 32 spring-boot-starter-test 33 test 34 35 36 org.junit.vintage 37 junit-vintage-engine 38 39 40 41 42 43 44 mysql 45 mysql-connector-java 46 47 48 49 50 com.alibaba 51 druid 52 1.1.10 53 54 55 56 org.springframework.boot 57 spring-boot-starter-data-jpa 58 59 60 org.springframework.boot 61 spring-boot-starter-cache 62 63 64 org.hibernate 65 hibernate-ehcache 66 67 68 69 70 71 72 org.springframework.boot 73 spring-boot-maven-plugin 74 75 76 77 78 src/main/resources 79 80 **/*.properties 81 **/*.yml 82 **/*.xml 83 **/*.p12 84 **/*.html 85 **/*.jpg 86 **/*.png 87 88 89 90 91 92
创建UserInfo实体类,如下所示: 1 package com.demo.po; 2 3 import javax.persistence.Cacheable; 4 import javax.persistence.Column; 5 import javax.persistence.Entity; 6 import javax.persistence.GeneratedValue; 7 import javax.persistence.GenerationType; 8 import javax.persistence.Id; 9 10 @Cacheable() 11 @Entity(name = "user_info") 12 public class UserInfo { 13 14 @Id() 15 @Column(name = "user_id") 16 @GeneratedValue(strategy = GenerationType.IDENTITY) // 根据名称引用配置的主键生成器 17 private Integer userId;// 用户编号 18 19 @Column(name = "user_account") 20 private String userAccount;// 用户账号 21 22 @Column(name = "user_pw") 23 private String userPw;// 用户密码 24 25 @Column(name = "user_number") 26 private String userNumber;// 用户学号 27 28 @Column(name = "user_name") 29 private String userName;// 用户姓名 30 31 @Column(name = "user_age") 32 private Integer userAge;// 用户年龄 33 34 @Column(name = "user_sex") 35 private String userSex;// 用户性别 36 37 @Column(name = "user_mark") 38 private String userMark;// 用户标识,可以使用一张表,完成管理员和用户 39 40 @Column(name = "is_money") 41 private String isMoney; 42 43 public Integer getUserId() { 44 return userId; 45 } 46 47 public void setUserId(Integer userId) { 48 this.userId = userId; 49 } 50 51 public String getUserAccount() { 52 return userAccount; 53 } 54 55 public void setUserAccount(String userAccount) { 56 this.userAccount = userAccount; 57 } 58 59 public String getUserPw() { 60 return userPw; 61 } 62 63 public void setUserPw(String userPw) { 64 this.userPw = userPw; 65 } 66 67 public String getUserNumber() { 68 return userNumber; 69 } 70 71 public void setUserNumber(String userNumber) { 72 this.userNumber = userNumber; 73 } 74 75 public String getUserName() { 76 return userName; 77 } 78 79 public void setUserName(String userName) { 80 this.userName = userName; 81 } 82 83 public Integer getUserAge() { 84 return userAge; 85 } 86 87 public void setUserAge(Integer userAge) { 88 this.userAge = userAge; 89 } 90 91 public String getUserSex() { 92 return userSex; 93 } 94 95 public void setUserSex(String userSex) { 96 this.userSex = userSex; 97 } 98 99 public String getUserMark() { 100 return userMark; 101 } 102 103 public void setUserMark(String userMark) { 104 this.userMark = userMark; 105 } 106 107 public String getIsMoney() { 108 return isMoney; 109 } 110 111 public void setIsMoney(String isMoney) { 112 this.isMoney = isMoney; 113 } 114 115 @Override 116 public String toString() { 117 return "UserInfo [userId=" + userId + ", userAccount=" + userAccount + ", userPw=" + userPw + ", userNumber=" 118 + userNumber + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex 119 + ", userMark=" + userMark + ", isMoney=" + isMoney + "]"; 120 } 121 122 }
创建UserDao,然后继承JpaRepository,此时就可以使用写好的方法了,不用自己再额外写接口和实现,如下所示: 1 package com.demo.dao; 2 3 import org.springframework.data.jpa.repository.JpaRepository; 4 5 import com.demo.po.UserInfo; 6 7 /** 8 * 9 * @author 继承JpaRepository包含全部的基础CURD操作 10 * 11 */ 12 public interface UserDao extends JpaRepository { 13 14 }
然后定义Service接口和Service接口实现,如下所示: 1 package com.demo.service; 2 3 import java.util.List; 4 5 import com.demo.po.UserInfo; 6 7 public interface UserService { 8 9 public List findAll(); 10 } 1 package com.demo.service.impl; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 8 import com.demo.dao.UserDao; 9 import com.demo.po.UserInfo; 10 import com.demo.service.UserService; 11 12 @Service 13 public class UserServiceImpl implements UserService { 14 15 @Autowired 16 private UserDao userDao; 17 18 @Override 19 public List findAll() { 20 21 return userDao.findAll(); 22 } 23 24 }
然后搞一个Controller,作为接口访问的入口,如下所示: 1 package com.demo.controller; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.ResponseBody; 9 10 import com.demo.po.UserInfo; 11 import com.demo.service.UserService; 12 13 @Controller 14 public class SpringBootController { 15 16 @Autowired 17 private UserService userService; 18 19 @RequestMapping(value = "/findAll") 20 @ResponseBody 21 public List findAll() { 22 List findAll = userService.findAll(); 23 return findAll; 24 } 25 26 }
修改程序启动主类,追加Repository扫描配置。如果使用JpaRepository实现了DAO接口的自动实现。需要注意的是,如果想启用Repository配置,则需要在程序启动主类时使用@EnableJpaRepositories注解配置扫描包,而后才可以正常使用。 1 package com.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 6 7 @SpringBootApplication // 启动Springboot程序,而后自带子包扫描 8 @EnableJpaRepositories(basePackages = "com.demo.dao") 9 public class DemoApplication { 10 11 public static void main(String[] args) { 12 // 启动Springboot程序 13 SpringApplication.run(DemoApplication.class, args); 14 } 15 16 }
修改application.properties,使用Druid作为数据源连接池,如下所示: 1 # mysql的数据库驱动 2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 3 # mysql的链接 4 spring.datasource.url=jdbc:mysql://localhost:3306/biehl 5 # mysql的账号 6 spring.datasource.username=root 7 # mysql的密码 8 spring.datasource.password=123456 9 10 # druid连接池的配置 11 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource 12 13 # Spring Data JPA,此配置可以在实体类中使用注解来创建数据表,开启正向工程 14 spring.jpa.hibernate.ddl-auto=update 15 # 在控制台打印sql语句 16 spring.jpa.show-sql=true
使用postman进行接口调用,如下所示:
最主要的是给自己增加知识的储备,有备无患。最后给大家分享Spring系列的学习笔记和面试题,包含spring面试题、spring cloud面试题、spring boot面试题、spring教程笔记、spring boot教程笔记、最新阿里巴巴开发手册(63页PDF总结)、2022年Java面试手册。一共整理了1184页PDF文档。私信博主(666)领取,祝大家更上一层楼!!!
特斯拉考虑开放自动驾驶技术,为什么华为最受影响?据国外媒体报道,特斯拉首席执行官埃隆马斯克最近表示,特斯拉正在考虑开源软件,对其他汽车制造商开放其自动驾驶技术。对于马斯克的言论,缸哥并没有感到意外。在不久前的特斯拉人工智能日上,
老牌电源厂商航嘉入局65W氮化镓口红电源在我的认知里,口红电源这个形态是联想最先推出的,之后就有越来越多的品牌跟进,基本上所有的口红电源都有氮化镓技术加持,几乎都是最高65W的输出功率,今天带来的这款65W氮化镓口红电源
一次咸鱼防骗经历虽说是个很小的事,钱也不多,但我遇上了就是要较真。前几天我在咸鱼30块挂了一个无线网卡,该买家上来并没有咨询关于该网卡的一切信息,直接就问25包邮可不可以,我答应了。该买家问我寄到
为旅行出差回家过年做好准备,便携大容量充电宝先看看它手机每年甚至每半年都在更新,各项先进功能硬件性能推陈出新,各种吸引广大幼少青中老年的应用和游戏也越来越多,但是有一个瓶颈始终未能获得突破,那就是待机时间,也就是电池,我们再也找不到
出差达人都在用这款出差神器,你确定不来一个?不当家不知道柴米贵不出差不知道出差难啊,出门在外,人生地不熟的,充个电都是麻烦事,这时候如果能够有一款移动电源可以实现给笔记本电脑补充能量,真的是人间幸事,最近出了个长差,也遇到了
继续折腾,安装黑威联通这几年以来,随着人们对数据存储的需求不断壮大,而百度网盘一家独大后的限速操作也助推家用NAS进入了寻常百姓家,当然其中有很大一部分用户是用矿渣刷的黑群晖,而群晖公司更是深得微软的真
会议记录好帮手,科大讯飞SR101录音笔工作十多年以来,这两年跟着领导开的会是最多的,当然了,开会肯定是要解决问题安排任务的,这时候如果稍微记错记漏一点,可能任务就会出现偏差,有一支快速操作拾音良好的录音笔就显得尤为重要
不能剪掉,那就藏起来奥睿科一体化收纳盒排插不论是工作还是生活,电脑桌面始终是一个不能避开的问题,桌面凌乱,是不是还在严重影响着你的工作心情?是不是很想把桌面上那些凌乱的电源线视频线数据线一把剪掉?桌面无线化肯定是解决这个问
AEB功能对行人无法有效刹停,理想汽车回应属实近日,拆车实验室对2021款理想ONE的辅助驾驶功能和自动紧急制动功能(AEB)进行了实测。结果显示2021款理想ONE的AEB功能无法在测试假人面前有效刹停,其辅助驾驶能力有效范
理想汽车公布二季度业绩,交付17575辆,汽车销售额49亿元8月30日,理想汽车公布了2021年第二季度财报。2021年第二季度,理想汽车营收50。4亿元,环比比上季度(35。8亿元)增长了40。9,其中,汽车销售收入为49亿元,环比增长4
试驾丨在车内躺平看电影!20万你会买智能百变的小鹏P5吗?五年前,若消费者预算20万左右,那么买轿车的话首选应是雅阁凯美瑞迈腾这类燃油B级车,而到了今天,家轿市场的格局已悄然发生改变,已经有越来越多新能源家轿加入战场,它们成为了消费者的新