您好,登錄后才能下訂單哦!
如何理解JpaRepository的關聯查詢和@Query查詢,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
<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> <groupId>org.fkit</groupId> <artifactId>springdatajpaquerytest</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springdatajpaquerytest</name> <url>http://maven.apache.org</url> <!-- spring-boot-starter-parent是Spring Boot的核心啟動器, 包含了自動配置、日志和YAML等大量默認的配置,大大簡化了我們的開發。 引入之后相關的starter引入就不需要添加version配置, spring boot會自動選擇最合適的版本進行添加。 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- 添加spring-boot-starter-web模塊依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 添加spring-boot-starter-thymeleaf模塊依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- 添加MySQL依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 添加Spring Data JPA依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
package org.fkit.springdatajpaquerytest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main( String[] args ) { // SpringApplication 用于從main方法啟動Spring應用的類。 SpringApplication.run(App.class, args); } }
######################################################## ### \u6570\u636E\u6E90\u4FE1\u606F\u914D\u7F6E ######################################################## # \u6570\u636E\u5E93\u5730\u5740 spring.datasource.url=jdbc:mysql://localhost:3306/springdatajpaquery # \u7528\u6237\u540D spring.datasource.username=root # \u5BC6\u7801 spring.datasource.password= # \u6570\u636E\u5E93\u9A71\u52A8 spring.datasource.driverClassName=com.mysql.jdbc.Driver # \u6307\u5B9A\u8FDE\u63A5\u6C60\u4E2D\u6700\u5927\u7684\u6D3B\u8DC3\u8FDE\u63A5\u6570. spring.datasource.max-active=20 # \u6307\u5B9A\u8FDE\u63A5\u6C60\u6700\u5927\u7684\u7A7A\u95F2\u8FDE\u63A5\u6570\u91CF. spring.datasource.max-idle=8 # \u6307\u5B9A\u5FC5\u987B\u4FDD\u6301\u8FDE\u63A5\u7684\u6700\u5C0F\u503C spring.datasource.min-idle=8 # \u6307\u5B9A\u542F\u52A8\u8FDE\u63A5\u6C60\u65F6\uFF0C\u521D\u59CB\u5EFA\u7ACB\u7684\u8FDE\u63A5\u6570\u91CF spring.datasource.initial-size=10 ######################################################## ### JPA\u6301\u4E45\u5316\u914D\u7F6E ######################################################## # \u6307\u5B9A\u6570\u636E\u5E93\u7684\u7C7B\u578B spring.jpa.database=MySQL # \u6307\u5B9A\u662F\u5426\u9700\u8981\u5728\u65E5\u5FD7\u4E2D\u663E\u793Asql\u8BED\u53E5 spring.jpa.show-sql=true # \u6307\u5B9A\u81EA\u52A8\u521B\u5EFA|\u66F4\u65B0|\u9A8C\u8BC1\u6570\u636E\u5E93\u8868\u7ED3\u6784\u7B49\u914D\u7F6E\uFF0C\u914D\u7F6E\u6210update # \u8868\u793A\u5982\u679C\u6570\u636E\u5E93\u4E2D\u5B58\u5728\u6301\u4E45\u5316\u7C7B\u5BF9\u5E94\u7684\u8868\u5C31\u4E0D\u521B\u5EFA\uFF0C\u4E0D\u5B58\u5728\u5C31\u521B\u5EFA\u5BF9\u5E94\u7684\u8868 spring.jpa.hibernate.ddl-auto=update # Naming strategy # \u6307\u5B9A\u547D\u540D\u7B56\u7565 spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy # \u6307\u5B9A\u6570\u636E\u5E93\u65B9\u8A00 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
springdatajpaquery
package org.fkit.springdatajpaquerytest.bean; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="tb_clazz") public class Clazz implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int code ; private String name ; // 班級與學生是一對多的關聯 @OneToMany( fetch=FetchType.LAZY, targetEntity=Student.class, mappedBy="clazz" ) private Set<Student> students = new HashSet<>(); public Clazz() { } // 班級對象 public Clazz(String name) { this.name = name; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } }
package org.fkit.springdatajpaquerytest.bean; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="tb_student") public class Student implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name ; private String address ; private int age ; private char sex; // 學生與班級是多對一的關系,這里配置的是雙向關聯 @ManyToOne(fetch=FetchType.LAZY, targetEntity=Clazz.class ) @JoinColumn(name="clazzId",referencedColumnName="code") private Clazz clazz ; public Student() { } public Student(String name, String address, int age, char sex, Clazz clazz) { super(); this.name = name; this.address = address; this.age = age; this.sex = sex; this.clazz = clazz; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } public Clazz getClazz() { return clazz; } public void setClazz(Clazz clazz) { this.clazz = clazz; } }
package org.fkit.springdatajpaquerytest.controller; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.fkit.springdatajpaquerytest.bean.Clazz; import org.fkit.springdatajpaquerytest.bean.Student; import org.fkit.springdatajpaquerytest.service.SchoolService; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/student") public class StudentController { // 注入ShcoolService @Resource private SchoolService schoolService; @RequestMapping("/save") public String save() { Clazz clazz1 = new Clazz("瘋狂java開發1班"); Clazz clazz2 = new Clazz("瘋狂java開發2班"); // 保存班級對象數據 List<Clazz> clazzs = new ArrayList<>(); clazzs.add(clazz1); clazzs.add(clazz2); schoolService.saveClazzAll(clazzs); Student swk = new Student("孫悟空","廣州",700,'男',clazz1); Student zzj = new Student("蜘蛛精","廣州",700,'女',clazz1); Student nmw = new Student("牛魔王","廣州",500,'男',clazz2); List<Student> students = new ArrayList<>(); students.add(swk); students.add(zzj); students.add(nmw); schoolService.saveStudentAll(students); return "保存學生對象成功"; } /** * 查詢某個班級下所有的學生姓名,年齡,性別 * @param clazzName * @return */ @RequestMapping("/getClazzStus") public List<Map<String, Object>> getClazzStus(String clazzName){ return schoolService.getStusByClazzName(clazzName); } /** * 查詢某個班級下所有的學生姓名,性別 * @param clazzName * @return */ @RequestMapping("/findNameAndSexByClazzName") public List<Map<String, Object>> findNameAndSexByClazzName(String clazzName){ return schoolService.findNameAndSexByClazzName(clazzName); } /** * ,查詢某個班級下某種性別的所有學生的姓名 * @param clazzName * @return */ @RequestMapping("/findNameByClazzNameAndSex") public List<String> findNameByClazzNameAndSex(String clazzName ,Character sex){ return schoolService.findNameByClazzNameAndSex(clazzName ,sex); } /** * 查詢某個學生屬于哪個班級 * @param clazzName * @return */ @RequestMapping("/findClazzNameByStuName") public String findClazzNameByStuName(String stuName){ return schoolService.findClazzNameByStuName(stuName); } /** * 刪除某個學生對象 * @param clazzName * @return */ @RequestMapping("/deleteStuByStuName") public String deleteStuByStuName(String stuName){ return "刪除數據:"+schoolService.deleteStuByStuName(stuName); } }
package org.fkit.springdatajpaquerytest.repository; import org.fkit.springdatajpaquerytest.bean.Clazz; import org.springframework.data.jpa.repository.JpaRepository; public interface ClazzRepository extends JpaRepository<Clazz, Integer> { }
package org.fkit.springdatajpaquerytest.repository; import java.util.List; import java.util.Map; import org.fkit.springdatajpaquerytest.bean.Student; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface StudentRepository extends JpaRepository<Student, Integer> { /** * 根據班級名稱查詢這個班級下所有的學生信息 * 相當于JPQL語句: select s from Student s where s.clazz.name = ?1 * @param clazzName * @return */ List<Student> findByClazz_name(String clazzName); /** * @Query寫法 * 根據班級名稱查詢這個班級下所有的學生信息 * ?1此處使用的是參數的位置,代表的是第一個參數 * 此寫法與 findByClazz_name方法實現的功能完全一致 * */ @Query("select s from Student s where s.clazz.name = ?1") List<Student> findStudentsByClazzName(String clazzName); /** * 使用@Query注解的形式,查詢某個班級下所有學生的姓名和性別 * @param clazzName * @return */ @Query("select new Map(s.name as name , s.sex as sex) " + "from Student s where s.clazz.name = ?1") List<Map<String, Object>> findNameAndSexByClazzName(String clazzName); /** * 使用@Query注解的形式,查詢某個班級下某種性別的所有學生的姓名 * 上面方法是用的是參數的位置來查詢的,Spring Data JPA中還支持用 * 名稱來匹配查詢使用格式 “:參數名稱” 引用 * @param clazzName * @return */ @Query("select s.name from Student s " + "where s.clazz.name = :clazzName and s.sex = :sex ") List<String> findNameByClazzNameAndSex(@Param("clazzName")String clazzName , @Param("sex")char sex); /** * 使用@Query注解的形式,查詢某個學生屬于哪個班級 * @param stuName * @return */ @Query("select c.name from Clazz c inner join c.students s " + "where s.name = ?1 ") String findClazzNameByStuName(String stuName); /** * 執行更新查詢,使用@Query與@Modifying可以執行更新操作 * 例如刪除牛魔王這個學生 * */ @Modifying @Query("delete from Student s where s.name = ?1") int deleteStuByStuName(String stuName); }
package org.fkit.springdatajpaquerytest.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.fkit.springdatajpaquerytest.bean.Clazz; import org.fkit.springdatajpaquerytest.bean.Student; import org.fkit.springdatajpaquerytest.repository.ClazzRepository; import org.fkit.springdatajpaquerytest.repository.StudentRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class SchoolService { // 注入數據訪問層接口對象 @Resource private StudentRepository studentRepository; @Resource private ClazzRepository clazzRepository; @Transactional public void saveClazzAll(List<Clazz> clazzs) { clazzRepository.saveAll(clazzs); } @Transactional public void saveStudentAll(List<Student> students) { studentRepository.saveAll(students); } public List<Map<String, Object>> getStusByClazzName(String clazzName) { // 使用"_" 和 @Query查詢方式結果一致 List<Student> students = studentRepository.findByClazz_name(clazzName); // List<Student> students = studentRepository.findStudentsByClazzName(clazzName); List<Map<String, Object>> results = new ArrayList<>(); // 遍歷查詢出的學生對象,提取姓名,年齡,性別信息 for(Student student:students){ Map<String , Object> stu = new HashMap<>(); stu.put("name", student.getName()); stu.put("age", student.getAge()); stu.put("sex", student.getSex()); results.add(stu); } return results; } public List<Map<String, Object>> findNameAndSexByClazzName(String clazzName) { return studentRepository.findNameAndSexByClazzName(clazzName); } public List<String> findNameByClazzNameAndSex( String clazzName, char sex) { return studentRepository.findNameByClazzNameAndSex(clazzName, sex); } public String findClazzNameByStuName(String stuName) { return studentRepository.findClazzNameByStuName(stuName); } @Transactional public int deleteStuByStuName(String stuName) { return studentRepository.deleteStuByStuName(stuName); } }
關于如何理解JpaRepository的關聯查詢和@Query查詢問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。