SpringBoot整合SpringDataJPA的示例
1.JPA是什么
首先,我們說(shuō)說(shuō)JPA是什么?
JPA(java persistence api),它并不是一個(gè)框架,而是一組規(guī)范。我覺(jué)得對(duì)于任何一個(gè)開發(fā)人員來(lái)說(shuō),理解“規(guī)范”這個(gè)詞應(yīng)該不在話下。其中,Hibernate就實(shí)現(xiàn)了這個(gè)規(guī)范,而且那是相當(dāng)成功的(其實(shí)TopLink和OpenJPA也都實(shí)現(xiàn)了JPA規(guī)范,不過(guò)它們被Hinernate的光環(huán)籠罩了)。所以呢,當(dāng)我們說(shuō)到JPA的時(shí)候,好多人首先想到的就是Hibernate。
2.SpringBootData JPA是什么
SpringData:其實(shí)SpringData就是Spring提供了一個(gè)操作數(shù)據(jù)的框架。而SpringData JPA只是SpringData框架下的一個(gè)基于JPA標(biāo)準(zhǔn)操作數(shù)據(jù)的模塊。
SpringData JPA:基于JPA的標(biāo)準(zhǔn)數(shù)據(jù)進(jìn)行操作。簡(jiǎn)化操作持久層的代碼。只需要編寫接口就可以。
廢話不多說(shuō)了,直接開始
3.環(huán)境/版本一覽
- 開發(fā)工具:Intellij IDEA 2020.2.3
- springboot:2.3.7.RELEASE
- jdk:1.8.0_211
- maven: 3.6.3
4.工程結(jié)構(gòu)
5.開始搭建
創(chuàng)建數(shù)據(jù)庫(kù)
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for sys_user -- ---------------------------- DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `pwd` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of sys_user -- ---------------------------- BEGIN; INSERT INTO `sys_user` VALUES (1, 'test', '123'); COMMIT; SET FOREIGN_KEY_CHECKS = 1;
新建項(xiàng)目
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.niu</groupId> <artifactId>datasource</artifactId> <version>1.0.0-SNAPSHOT</version> <name>datasource</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!-- alibaba的druid數(shù)據(jù)庫(kù)連接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
創(chuàng)建配置文件 application.yml
server: port: 8080 spring: datasource: name: main_db type: com.alibaba.druid.pool.DruidDataSource #druid相關(guān)配置 druid: #監(jiān)控統(tǒng)計(jì)攔截的filters filters: stat driver-class-name: com.mysql.jdbc.Driver #基本屬性 url: jdbc:mysql://127.0.0.1:3306/t_user_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true username: root password: Abcdef@123456 #配置初始化大小/最小/最大 initial-size: 1 min-idle: 1 max-active: 20 #獲取連接等待超時(shí)時(shí)間 max-wait: 60000 #間隔多久進(jìn)行一次檢測(cè),檢測(cè)需要關(guān)閉的空閑連接 time-between-eviction-runs-millis: 60000 #一個(gè)連接在池中最小生存的時(shí)間 min-evictable-idle-time-millis: 300000 validation-query: SELECT 'x' test-while-idle: true test-on-borrow: false test-on-return: false #打開PSCache,并指定每個(gè)連接上PSCache的大小。oracle設(shè)為true,mysql設(shè)為false。分庫(kù)分表較多推薦設(shè)置為false pool-prepared-statements: false max-pool-prepared-statement-per-connection-size: 20 jpa: hibernate: ddl-auto: update show-sql: true
創(chuàng)建model 類多的話可以使用逆向工程創(chuàng)建
@Entity(name = "sys_user") //name值代表數(shù)據(jù)庫(kù)對(duì)應(yīng)的表名,如不寫默認(rèn)按照實(shí)體類的駝峰命名法單詞中間加_ @JsonIgnoreProperties(value = { "hibernateLazyInitializer"}) //加這個(gè)注解是為了防止本項(xiàng)目把jpa對(duì)象直接轉(zhuǎn)json有空值報(bào)錯(cuò) public class SysUser { @Id @GeneratedValue private Integer id; /** * * 這里是映射數(shù)據(jù)表字段與實(shí)體字段 若數(shù)據(jù)庫(kù)表字段為 user_name 這里需要寫成 * @Column(name = "user_name") * private String userName; * 如果一致可以不寫 */ @Column(name = "name") private String name; private String pwd; //get/set省略,記得加上 }
創(chuàng)建Repository
/** * * JpaRepository<SysUser,Integer> 參數(shù)1 要映射的實(shí)體類 * 參數(shù)2 實(shí)體類主鍵的數(shù)據(jù)類型 * 每個(gè)dao層接口都要繼承這個(gè)類 **/ @Repository public interface SysUserRepository extends JpaRepository<SysUser,Integer> { }
創(chuàng)建service
@Service public class UserService { @Autowired private SysUserRepository sysUserRepository; public SysUser getUser(Integer id){ return sysUserRepository.getOne(id); } }
創(chuàng)建controller 這里我們讓接口都返回json 使用@RestController注解
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{userId}") public SysUser user(@PathVariable Integer userId){ return userService.getUser(userId); } }
創(chuàng)建主類
@SpringBootApplication public class SpringbootJPAApplication { public static void main(String[] args) { SpringApplication.run(SpringbootJPAApplication.class, args); } }
6.啟動(dòng)測(cè)試
查看下日志:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.7.RELEASE)2020-12-17 10:05:32.976 INFO 3434 --- [ main] c.n.springboot.SpringbootJPAApplication : Starting SpringbootJPAApplication on MacBook-Pro.local with PID 3434 (/Users/laoniu/IdeaProjects/datasource/target/classes started by laoniu in /Users/laoniu/IdeaProjects/datasource)
2020-12-17 10:05:32.979 INFO 3434 --- [ main] c.n.springboot.SpringbootJPAApplication : No active profile set, falling back to default profiles: default
2020-12-17 10:05:33.606 INFO 3434 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-12-17 10:05:33.668 INFO 3434 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 55ms. Found 1 JPA repository interfaces.
2020-12-17 10:05:34.014 INFO 3434 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-12-17 10:05:34.021 INFO 3434 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-12-17 10:05:34.021 INFO 3434 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.41]
2020-12-17 10:05:34.096 INFO 3434 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-12-17 10:05:34.096 INFO 3434 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1058 ms
2020-12-17 10:05:34.150 INFO 3434 --- [ main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
Thu Dec 17 10:05:34 CST 2020 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
2020-12-17 10:05:34.627 INFO 3434 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
2020-12-17 10:05:34.774 INFO 3434 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-12-17 10:05:34.807 INFO 3434 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.25.Final
2020-12-17 10:05:34.903 INFO 3434 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2020-12-17 10:05:34.981 INFO 3434 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
2020-12-17 10:05:35.360 INFO 3434 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-12-17 10:05:35.367 INFO 3434 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-12-17 10:05:35.580 WARN 3434 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-12-17 10:05:35.680 INFO 3434 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-12-17 10:05:35.878 INFO 3434 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-12-17 10:05:35.890 INFO 3434 --- [ main] c.n.springboot.SpringbootJPAApplication : Started SpringbootJPAApplication in 3.227 seconds (JVM running for 3.93)
2020-12-17 10:05:49.330 INFO 3434 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-12-17 10:05:49.331 INFO 3434 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-12-17 10:05:49.335 INFO 3434 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 4 ms
Hibernate: select sysuser0_.id as id1_0_0_, sysuser0_.name as name2_0_0_, sysuser0_.pwd as pwd3_0_0_ from sys_user sysuser0_ where sysuser0_.id=?
可以看到最后一行是SpringDataJPA為我們生成的查詢語(yǔ)句,我們并沒(méi)有寫sql,只是調(diào)用的SpringDataJPA自帶的方法,讓我們?nèi)タ匆幌耂pringDataJPA都為我們提供哪些可用的方法
7.Repository接口的使用
7.1SpringDataJPA提供的方法
按照SpringDataJPA規(guī)范可以讓我們只寫方法就可以進(jìn)行操作數(shù)據(jù)庫(kù),讓我們?cè)囈幌?/p>
7.2編寫Repository接口方法
//方法名稱必須要遵循駝峰式命名規(guī)則,findBy(關(guān)鍵字)+屬性名稱(首字母大寫)+查詢條件(首字母大寫) SysUser findByNameAndPwd(String name,String pwd);
這樣就能完成基本的查詢
刪除用deleteBy開頭方法
如果方法不能滿足我的需求呢,我們還可以通過(guò)@Query注解手動(dòng)寫sql
8.@Query基本使用
/*** * * ?1表示第一個(gè)參數(shù),?2表示第二個(gè)參數(shù) * 這里的寫法是hql寫法 * nativeQuery = false 代表使用hql ,默認(rèn)不設(shè)置的話就是false 默認(rèn)使用的hql * 要想使用 原生的sql 改為 true即可 */ @Query(value = "from SysUser where name = ?1 and pwd =?2",nativeQuery = false) SysUser findByNameAndPwdUseSQL(String name,String pwd);
到此,SpringBoot整合SpringDataJPA基本的使用結(jié)束,代碼已經(jīng)推送至github,https://github.com/NiuXiangQian/springboot-jpa
到此這篇關(guān)于SpringBoot整合SpringDataJPA的示例的文章就介紹到這了,更多相關(guān)SpringBoot整合SpringDataJPA內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java String字符串和Unicode字符相互轉(zhuǎn)換代碼詳解
這篇文章主要介紹了Java String字符串和Unicode字符相互轉(zhuǎn)換代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05JWT 設(shè)置token過(guò)期時(shí)間無(wú)效的解決
這篇文章主要介紹了JWT 設(shè)置token過(guò)期時(shí)間無(wú)效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07使用SpringBoot中的Schedule定時(shí)發(fā)送郵件的方法
在SpringBoot中,你可以使用@Scheduled注解來(lái)創(chuàng)建定時(shí)任務(wù),@Scheduled注解可以應(yīng)用于方法上,表示這個(gè)方法是一個(gè)定時(shí)任務(wù),可以根據(jù)指定的時(shí)間間隔或固定時(shí)間執(zhí)行,本文就給大家介紹一下如何使用SpringBoot中的Schedule定時(shí)發(fā)送郵件,需要的朋友可以參考下2023-08-08Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(62)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-08-08