日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot开发案例之整合Spring-data-jpa

發(fā)布時間:2023/12/20 javascript 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot开发案例之整合Spring-data-jpa 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

什么是spring-data

為了簡化程序與數(shù)據(jù)庫交互的代碼,spring提供了一個現(xiàn)成的dao層框架,spring家族提供的spring-data適用于關(guān)系型數(shù)據(jù)庫和nosql數(shù)據(jù)庫

什么是jpa

JPA全稱為Java持久性API(Java Persistence API),JPA是java EE 5標(biāo)準(zhǔn)之一,是一個ORM規(guī)范,由廠商來實現(xiàn)該規(guī)范,目前有hibernate、OpenJPA、TopLink、EclipseJPA等實現(xiàn)。

如何使用JPA

查詢

  • 查詢所有數(shù)據(jù) findAll()
  • 分頁查詢 findAll(new PageRequest(0, 2))
  • 根據(jù)id查詢 findOne()
  • 根據(jù)實體類屬性查詢: findByProperty (type Property); 例如:findByAge(int age);
  • 排序: findAll(sort )
  • Sort sort = new Sort(Sort.Direction.DESC, "age").and (new Sort(Sort.Direction.DESC, "id"));
  • 條件查詢 and/or/findByAgeLessThan/LessThanEqual 等,
  • 例如: findByUsernameAndPassword(String username , String password)
  • 總數(shù) 查詢 count() 或者 根據(jù)某個屬性的值查詢總數(shù)countByAge(int age);
  • 是否存在某個id exists()

修改,刪除,新增

  • 新增:直接使用 save(T) 方法
  • 刪除: delete() 或者 deleteByProperty 例如:deleteByAge(int age) ;
  • 更新:
    @Modifying?
    @Query("update Customer u set u.age = ?1 where u.id = ?2")
    int update(int age1 , long id);

項目結(jié)構(gòu)

相關(guān)配置

pom.xml(部分代碼,詳見源碼):

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

application.properties:

# 項目contextPath server.context-path=/jpa # 服務(wù)端口 server.port=8080 # session最大超時時間(分鐘),默認(rèn)為30 server.session-timeout=60 # 該服務(wù)綁定IP地址,啟動服務(wù)器時如本機不是該IP地址則拋出異常啟動失敗,只有特殊需求的情況下才配置 #server.address=192.168.1.66# tomcat最大線程數(shù),默認(rèn)為200 server.tomcat.max-threads=100 # tomcat的URI編碼 server.tomcat.uri-encoding=UTF-8#注意中文亂碼 spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123 spring.datasource.driver-class-name=com.mysql.jdbc.Driver # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Default to "create-drop" when using an embedded database, "none" otherwise. spring.jpa.hibernate.ddl-auto = update # Hibernate 4 naming strategy fully qualified name. Not supported with Hibernate 5. spring.jpa.hibernate.naming.strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置屬性,其主要作用是:自動創(chuàng)建、更新、驗證數(shù)據(jù)庫表結(jié)構(gòu)。該參數(shù)的幾種配置如下:

  • create:每次加載hibernate時都會刪除上一次的生成的表,然后根據(jù)你的model類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執(zhí)行,這就是導(dǎo)致數(shù)據(jù)庫表數(shù)據(jù)丟失的一個重要原因。
  • create-drop:每次加載hibernate時根據(jù)model類生成表,但是sessionFactory一關(guān)閉,表就自動刪除。
  • update:最常用的屬性,第一次加載hibernate時根據(jù)model類會自動建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫),以后加載hibernate時根據(jù)model類自動更新表結(jié)構(gòu),即使表結(jié)構(gòu)改變了但表中的行仍然存在不會刪除以前的行。要注意的是當(dāng)部署到服務(wù)器后,表結(jié)構(gòu)是不會被馬上建立起來的,是要等應(yīng)用第一次運行起來后才會。
  • validate:每次加載hibernate時,驗證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),只會和數(shù)據(jù)庫中的表進(jìn)行比較,不會創(chuàng)建新表,但是會插入新值。

實體類 User.java:

package com.itstyle.jpa.model; import java.io.Serializable; import javax.persistence.*; /*** 用戶實體(此處注意引用的注解包為javax.persistence*下面的)* 創(chuàng)建者 科幫網(wǎng)* 創(chuàng)建時間 2017年7月25日**/ @Entity @Table(name = "sys_user") public class User implements Serializable{private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.AUTO)@Column(name = "id", nullable = false)private Long id;@Column(nullable = false, name = "name")private String name;@Column(nullable = false, name = "age")private Integer age;--- 省略 get set 方法 }

數(shù)據(jù)操作UserRepository.java:

/*** 數(shù)據(jù)操作層* 創(chuàng)建者 科幫網(wǎng)* 創(chuàng)建時間 2017年7月25日**/ public interface UserRepository extends JpaRepository<User, Long> {User findByName(String name);User findByAge(Integer age);User findByNameAndAge(String name, Integer age);List<User> findByNameLike(String name);@Query("from User u where u.name=:name")User findUser(@Param("name") String name);}

小伙伴沒有沒有發(fā)現(xiàn),我們只是定義了一個方法而已,怎么就這么奇妙的實現(xiàn)的對應(yīng)功能?其實這是Spring-data-jpa的新特性,通過解析方法名創(chuàng)建查詢。更多解析說明如下:

And => 等價于 SQL 中的 and 關(guān)鍵字 例如:findByUsernameAndPassword(String user, Striang pwd);
Or => 等價于 SQL 中的 or 關(guān)鍵字,例如:findByUsernameOrAddress(String user, String addr);
Between => 等價于 SQL 中的 between 關(guān)鍵字,例如:SalaryBetween(int max, int min);
LessThan => 等價于 SQL 中的 "<",例如: findBySalaryLessThan(int max);
GreaterThan => 等價于 SQL 中的">",例如: findBySalaryGreaterThan(int min);
IsNull => 等價于 SQL 中的 "is null",例如: findByUsernameIsNull();
IsNotNull => 等價于 SQL 中的 "is not null",例如: findByUsernameIsNotNull();
NotNull=> 與 IsNotNull 等價;
Like => 等價于 SQL 中的 "like",例如: findByUsernameLike(String user);
NotLike => 等價于 SQL 中的 "not like",例如: findByUsernameNotLike(String user);
OrderBy => 等價于 SQL 中的 "order by",例如: findByUsernameOrderBySalaryAsc(String user);
Not => 等價于 SQL 中的 "! =",例如: findByUsernameNot(String user);
In => 等價于 SQL 中的 "in",例如: findByUsernameIn(Collection userList) ,方法的參數(shù)可以是 Collection 類型,也可以是數(shù)組或者不定長參數(shù);
NotIn => 等價于 SQL 中的 "not in",例如: findByUsernameNotIn(Collection userList) ,方法的參數(shù)可以是 Collection 類型,也可以是數(shù)組或者不定長參數(shù);
創(chuàng)建一個按單字段排序的Sort對象: new Sort(Sort.Direction.DESC, "description").and(new Sort(Sort.Direction.ASC, "id"))

最終測試類SpringbootJpaApplication.java:

package com.itstyle.jpa;import java.util.List;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;import com.itstyle.jpa.model.User; import com.itstyle.jpa.repository.UserRepository;@SpringBootApplication public class SpringbootJpaApplication implements CommandLineRunner {@Autowiredprivate UserRepository userRepository;public static void main(String[] args) {SpringApplication.run(SpringbootJpaApplication.class, args);}@Overridepublic void run(String... args) throws Exception {try {User user = new User();user.setName("張三");user.setAge(20);userRepository.save(user);List<User> u = userRepository.findByNameLike("%張三%");System.out.println(u.size());User us = userRepository.findByAge(20);System.out.println(us.getAge());us = userRepository.findByName("這是你干");} catch (Exception e) {e.printStackTrace();}} }

偶遇問題

No identifier specified for entity:

檢查一下包是否引入正確,引入一下:

import javax.persistence.*;

中文亂碼問題:

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8

在高版本mysql中需要指定是否進(jìn)行SSL連接

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false

代碼:https://git.oschina.net/52itstyle/spring-data-jpa

作者: 小柒

出處:?https://blog.52itstyle.com

轉(zhuǎn)載于:https://www.cnblogs.com/walblog/articles/9483296.html

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結(jié)

以上是生活随笔為你收集整理的SpringBoot开发案例之整合Spring-data-jpa的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。