Il existe deux méthodes d'implémentation pour les requêtes multiples dans les données de printemps JPA. La première consiste à utiliser Hibernate Cascade Query pour l'implémenter, et la seconde consiste à créer une interface de jeu de résultats pour recevoir les résultats après la requête de table connectée. Voici une deuxième méthode.
1. Mappage individuel
Entité UserInfo: utilisateur.
Adresse de l'entité: adresse de la maison.
Ici, une association individuelle est réalisée grâce à la méthode de la clé étrangère (une entité est associée à la clé principale d'une autre entité par le biais d'une clé étrangère).
Classe d'entité
1. ENTITY CLASS UserInfo.java
Package com.johnfnash.learn.domain; importer java.io.serializable; import javax.persistence.entity; import javax.persistence.generatedvalue; import javax.persistence.generationtype; import javax.persistence.id; Importer javax.persistence.tel UserInfo implémente Serializable {private static final long SerialVersionUID = 8283950216116626180l; @Id @GeneratedValue (Strategy = GenerationType.Identity) Private Long UserId; nom de chaîne privé; Âge privé; Sexe à cordes privées; e-mail de chaîne privée; // Association avec l'adresse Private Long Address; public userInfo () {super (); } public userInfo (nom de chaîne, int, sexe de la chaîne, courriel de chaîne, longadred) {super (); this.name = name; this.age = âge; this.sex = sexe; this.email = e-mail; this.AddressId = AddressId; } // getter, seter @Override public String toString () {return String.Format ("userInfo [userId =% d, name =% s, age =% s, sexe =% s, e-mail =% s]", utilisateur, nom, âge, sexe, e-mail); }} 2. Adresse de la classe d'entité.java
Package com.johnfnash.learn.domain; import javax.persistence.entity; import javax.persistence.generatedvalue; import javax.persistence.generationtype; import javax.persistence.id; import javax.persistence.Table; @ entité @ table (nom = "tb_address") @GeneratedValue (Strategy = GenerationType.Identity) privé Address LongId; STRING PRIVÉ AreaCode; pays de cordes privées; Province privée de cordes; ville de cordes privée; zone de chaîne privée; String DetailAddress privé; Adresse publique () {super (); } Adresse publique (String Areacode, String Country, String Province, String City, String Area, String DetailAddress) {super (); this.ARACODE = Areacode; this.country = pays; this.province = province; this.city = ville; this.aria = zone; this.detailAddress = DetailAddress; } // getter, seter @Override public String toString () {return "Address [Address =" + Address + ", Areacode =" + Areacode + ", country =" + country + ", province =" + province + ", city =" + city + ", area =" + area + ", de détailAddress =" + DetailAddress + "]"; }} Couche DAO
1. UserInforepository.java
package com.johnfnash.learn.repository; import java.util.list; import org.springframework.data.jpa.repository.jParepository; import org.springframework.data.jpa.repository.query; import com.johnfnash.learn.Domain.USERING com.johnfnash.learn.domain.ViewInfo; Interface publique UserInforepository étend JParePository <userInfo, Long> {@Query (Value = "Select New Com.Johnfnash.Learn.Domain.ViewInfo (U, A) sur UserInfo U, Adresse a Where U.AdDressId = A.ADDRESSID") Public Liste <ViewInfo> findViewInfo ();} Remarque: La classe ViewInfo ici est utilisée pour recevoir des ensembles de résultats de requête multipliques (en utilisant un nouveau constructeur de nom de classe complet)
Le code est le suivant:
package com.johnfnash.learn.domain; import java.io.serializable; public class ViewInfo implémente Serializable {private static final SerialVersionUID = -6347911007178390219l; UserInfo privé UserInfo; adresse privée; public ViewInfo () {} public ViewInfo (userInfo userInfo) {adresse Adresse = new Address (); this.UserInfo = userInfo; this.address = adresse; } public ViewInfo (adresse d'adresse) {userInfo userInfo = new UserInfo (); this.UserInfo = userInfo; this.address = adresse; } public ViewInfo (userInfo userInfo, adresse d'adresse) {this.UserInfo = userInfo; this.address = adresse; } // Getter, setter} 2. AddressRepository.java
package com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jParepository; importation com.johnfnash.learn.domain.address; interface publique AddressRepository étend JParepository <adresse, {} Code de test
package com.johnfnash.learn; import java.util.list; import org.junit.after; import org.junit.before; import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowired; importation; org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4 com.johnfnash.learn.repository.addressrepository; import com.johnfnash.learn.repository.userinforepository; @runwith (springrunner.class) @springboottestPublic class userInforepositorytests {@Autowired private userInForepository userIrinforestorepository; @Autowired private AddressRepository AddressRepository; @Before public void init () {adresse addr1 = new adress ("027", "cn", "hubei", "wuhan", "wuchang", "123 street"); Adresse addr2 = nouvelle adresse ("023", "cn", "chongqing", "chongqing", "yubei", "123 road"); AddressRepository.save (Addr1); AddressRepository.save (addr2); UserInfo user1 = new UserInfo ("zs", 21, "mâle", "[email protected]", addr1.getAddressID ()); UserInfo user2 = new UserInfo ("ww", 25, "mâle", "[email protected]", addr2.getAddressID ()); userInForepository.save (user1); userInForepository.save (user2); } @After public void Deleteall () {userInForepository.DeleTeall (); AddressRepository.DeleTeall (); } @Test public void testQuery () {list <ViewInfo> ViewInfos = userInForepository.FindViewInfo (); for (ViewInfo ViewInfo: ViewInfos) {System.out.println (ViewInfo.getUserInfo ()); System.out.println (ViewInfo.getAddress ()); }}}Le SQL lié à la requête est le suivant:
Hibernate: Sélectionnez UserInfo0_.User_Id en tant que col_0_0_, adresse1_.address_id en tant que col_1_0_ à partir de TB_USER UserInfo0_ userInfo0_.address_id as adresse_2_4_0_, userInfo0_.age as Age3_4_0_, userInfo0_.email as e-mail4_4_0_, userInfo0_.name as name5_4_0_ userInfo0_.user_id =? HiberNate: Sélectionnez Adresse0_.Address_id as Address_1_3_0_, adresse0_.Area as Area2_3_0_, Address0_.Area_code as Area_Cod3_3_0_, Address0_.City As City4_3_.Ded_Address As As Country5_3_0_ Détail_A6_3_0_, adresse0_.province as province7_3_0_ à partir de tb_address adress0_ où adresse0_.address_id =? hibernate: sélectionnez userInfo0_.user_id as user_id1_4_0_, userInfo0_.age userInfo0_.email as e-mail4_4_0_, userInfo0_.name as name5_4_0_, userInfo0_.sex as sex6_4_0_ à partir de tb_user userInfo0_ où userInfo0_.User_id =? Hibernate: Sélectionner Address0_.address_id as adresse_1_3_0_, Address0_. Area2_3_0_, adresse0_.area_code as area_cod3_3_0_, adresse0_.city as city4_3_0_, adresse0_.country as country5_3_0_, adress0_.detail_address as détaillé_a6_3_0_, adresse0_. adresse0_.address_id =? hibernate: sélectionnez userInfo0_.user_id as user_id1_4_, userInfo0_.address_id as adresse_2_4_, userInfo0_.age en tant qu'âge 3_4_, userInfo0_.email comme e-mail4_4_ Sex6_4_ à partir de tb_user userInfo0_hibernate: sélectionnez adresse0_.address_id as adresse_1_3_, adresse 0_.area as area2_3_, adresse 0_.area_code as area_cod3_3_, adresse0_.city as ville4_3_, adresse Detail_A6_3_, adresse0_.province as province7_3_ de TB_ADdress Address0_
Les résultats de la requête sont les suivants:
UserInfo [userId = 1, name = zs, âge = 21, sexe = mâle, [email protected]]
Adresse [AddressId = 1, AreaCode = 027, pays = CN, province = Hubei, ville = Wuhan, Area = Wuchang, DetailAddress = 123 Street]
UserInfo [userId = 2, name = ww, âge = 25, sexe = mâle, [email protected]]
Address [AddressId = 2, AreaCode = 023, pays = CN, province = Chongqing, ville = Chongqing, zone = yubei, détailAddress = 123 Road]
2. Cartographie de plusieurs à plusieurs
Auteur de l'entité: Auteur.
Livre d'entité: livres
Ici, l'association de plusieurs à plusieurs est obtenue par le biais du tableau d'association.
Classe d'entité
Classe d'entité: auteur.java
Package com.johnfnash.learn.domain; import java.io.serializable; import javax.persistence.entity; import javax.persistence.generatedValue; import javax.persistence.id; @entityPublic classing itallizable {private static final Serrialversiid = 1227555587798655046l; @Id @GeneratedValue ID entier privé; nom de chaîne privé; Auteur public () {super (); } Auteur public (nom de chaîne) {super (); this.name = name; } // getter, seter @Override public String toString () {return String.Format ("auteur [id =% s, name =% s]", id, name); }} Classe d'entité book.java
package com.johnfnash.learn.domain; import java.io.serializable; import javax.persistence.entity; import javax.persistence.generatedValue; import javax.persistence.id; @entityPublic class book mettelable {private static final Serrialversionuid = -2470510857424220408L; @Id @GeneratedValue ID entier privé; nom de chaîne privé; livre public () {super (); } livre public (nom de chaîne) {super (); this.name = name; } // getter, seter @Override public String toString () {return String.format ("book [id =% s, name =% s]", id, name); }} BookAuthor de classe d'entité.java
Package com.johnfnash.learn.domain; importer javax.persistence.entity; import javax.persistence.id; import javax.persistence.idclass; import javax.persistence.table; @ entité @ idclass (bookAuthorpk.class) @Table (name = "book_author") Classique publique bookaThor {@id private; book_author ") Classique publique bookaThor {@id private; @Id Private Integer AuthorId; BookAuthor public () {super (); } public bookauthor (Integer bookId, entier autorid) {super (); this.bookid = bookid; this.Authorid = AuthorId; } // Getter, setter}Remarque: Ici, nous utilisons l'annotation @IDClass pour spécifier une classe de clé primaire syndicale pour mapper plusieurs propriétés de la classe d'entité. Le code de cette classe de clé primaire conjointe est la suivante:
package com.johnfnash.learn.domain; import java.io.serializable; classe publique bookAuthorpk implémente serializable {private static final SerialVersionUID = -1158141803682305656l; Bookid entier privé; Auteur entier privé; public entier getBookId () {return bookId; } public void setBookId (Integer bookId) {this.bookId = bookId; } public Integer getAuthorid () {return AuthorId; } public void setAuthorid (Integer AuthorId) {this.Authorid = AuthorId; }} Couche DAO
BookRepository.java
package com.johnfnash.learn.repository; import java.util.list; import org.springframework.data.jpa.repository.jparepository; import org.springframework.data.jpa.repository.query; importation bookrewe JParePository <Book, Integer> {@Query (nativeQuery = true, Value = "Select B.Id, B.Name, Group_Concat (A.Name) comme authorname from Book B, Author A, book_author ba" + "WHERE B.ID = ba.book_id et a.id = ba.author_id et b.name like? 1 Group by B.id, B.Name") findByNameConting (nom de la chaîne);} Note:
1) Ici, NativeQuery = True Spécifie que l'utilisation de SQL native est utilisée pour l'interrogation (je pense personnellement qu'il est préférable d'utiliser SQL natif pour des requêtes complexes.
2) Ici, la fonction intégrée de MySQL Group_Concat est utilisée pour la conversion de ligne à colonne, et HQL ne peut pas être directement reconnu. Causé par: org.hibernate.queryException: aucun type de données pour le nœud: org.hibernate.hql.internal.ast.tree.methodnode peut se produire
JParePository.java
package com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jParepository; import com.johnfnash.learn.domain.author; Interface publique auteur de lapository étend JPareOspository <auteur, entier> {} BookAuthorRepository.java
Package com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jParepository; import com.johnfnash.learn.domain.bookAuthor
Code de test
package com.johnfnash.learn; import static org.junit.assert.assertequals; import java.util.list; import org.junit.after; import org.junit.before; import org.junit.test; import org.junit.runner.runwith; importation; org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; import org.springframework.test.Con com.johnfnash.learn.domain.book; import com.johnfnash.learn.domain.bookAuthor; import com.johnfnash.learn.repository.authorrepository; import. com.johnfnash.learn.repository.bookRepository; @runwith (springrunner.class) @springboottestpublic bookRepositorytests {@autowired bookRepository bookRepository; @Autowired Private AuthorRepository AuthorRepository; @Autowired private bookAuthorRepository bookAuthorRepository; @Before public void init () {auteur lewis = nouvel auteur ("Lewis"); Auteur Mark = nouvel auteur ("Mark"); Auteur Peter = nouvel auteur ("Peter"); AuthorRepository.save (Lewis); AuthorRepository.save (Mark); AuthorRepository.Save (Peter); Livre printemps = nouveau livre ("Spring in Action"); Livre Springboot = nouveau livre ("Spring Boot in Action"); bookRepository.save (printemps); bookRepository.save (Springboot); bookAuthorRepository.save (new bookAuthor (spring.getId (), lewis.getID ())); bookAuthorRepository.save (new bookAuthor (printemps.getId (), mark.getId ())); bookAuthorRepository.save (new bookAuthor (sningboot.getId (), mark.getId ())); bookAuthorRepository.save (New BookAuthor (Springboot.getID (), Peter.getID ())); } @After public void Deleteall () {bookAuthorRepository.deleteall (); bookRepository.deleteall (); authorrepository.deleteall (); } @Test public void findall () {asserTequals (bookRepository.findall (). Size (), 2); asserTequals (authorrepository.findall (). size (), 3); List <object []> books = bookRepository.findByNameContaining ("Spring%"); for (object [] book: books) {for (objet objet: book) {System.out.print (objet + ","); } System.out.println (); }}}Après avoir exécuté la méthode Findall, le SQL pertinent pour la requête est le suivant:
Hibernate: SELECT B.ID, B.NAME, GROUP_CONCAT (A.NAME) AS Authorname From Book B, Author A, Book_Author BA WHERE B.ID = ba.book_id et a.id = ba.author_id et b.name comme? Groupe par B.Id, B.Name
Les résultats de sortie sont les suivants:
3652, printemps en action, Lewis, Mark,
3653, Spring Boot in Action, Mark, Peter,
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.