Es gibt zwei Implementierungsmethoden für Multi-Table-Abfragen in den Frühlingsdaten JPA. Die erste besteht darin, eine Hibernate -Cascade -Abfrage zu verwenden, um sie zu implementieren, und das zweite besteht darin, eine Ergebnis -Set -Schnittstelle zu erstellen, um die Ergebnisse nach der angeschlossenen Tabellenabfrage zu empfangen. Hier ist eine zweite Methode.
1. Ein-zu-Eins-Zuordnung
Entity userInfo: Benutzer.
Entitätsadresse: Home -Adresse.
Hier wird ein Eins-zu-Eins-Verband durch die ausländische Schlüsselmethode erreicht (eine Entität ist mit dem Primärschlüssel eines anderen Unternehmens durch einen Fremdschlüssel verbunden).
Entitätsklasse
1. Entity -Klasse userInfo.java
Paket com.johnfnash.learn.domain; import Java.io.Serializable; Import Javax.Persistence.Entity; Import Javax.Persistence.generatedValue; Import Javax.Persistence.generationType; UserInfo implementiert serialisierbar {private statische endgültige long serialversionuid = 8283950216116626180L; @ID @generatedValue (Strategy = GenerationType.Identity) Private Long UserId; privater Zeichenfolge Name; privates int Alter; privater String Sex; private Zeichenfolge E -Mail; // Assoziation mit der Adresse Private Long AdDID; public userInfo () {super (); } public userInfo (String -Name, int Alter, String Sex, String -E -Mail, Long addressID) {Super (); this.name = name; this.age = Alter; this.sex = sex; this.email = E -Mail; this.addressid = addresID; } // Getter, setzter @Override public String toString () {return string.format ("userInfo [userId =%d, name =%s, alter =%s, sex =%s, E -Mail =%s]", userId, name, ay, sex, E -Mail); }} 2. Entitätsklassenadresse.java
Paket com.johnfnash.learn.domain; import Javax.Persistence.Entity; Import Javax.Persistence.generatedValue; Import Javax.Persistence.generationType; Bedeutung Javax.Persistence.id; @GeneratedValue (Strategie = GenerationType.Identity) Private Long AdressID; private String AreaCode; privates Saitenland; private String -Provinz; private Streichstadt; privates Saitenbereich; private String -DetailAddress; öffentliche Adresse () {Super (); } öffentliche Adresse (String AreaCode, String Country, String Provinz, String City, String Area, String DetailAddress) {Super (); this.areacode = AreaCode; this.country = Land; this.Province = Provinz; this.city = Stadt; this.Area = Bereich; this.detailaddress = detailAddress; } // Getter, setzter @Override public String toString () {return "address [adressId =" + adressid + ", AreaCode =" + AreaCode + ", Country =" + Country + ", provinz =" + provinz + ", city =" + city + ", aa" + ases detailaddress = "detailAddress +". }} DAO -Schicht
1. userInforePository.java
Paket com.johnfnash.learn.repository; import java.util.list; import org.springframework.data.jpa.repository.jparepository; com.johnfnash.learn.domain.viewInfo; public interface userInforePository erweitert JParepository <userInfo, long> {@Query (value = "Wählen Sie neue com.johnfnash.learn.domain.viewInfo (u, a) von userInfo u, wob findViewInfo ();} HINWEIS: Die ViewInfo-Klasse hier wird verwendet, um Abfrageergebnis-Sets mit Multi-Tabellen zu empfangen (mit dem neuen Konstruktor des vollständigen Klassennamens)
Der Code ist wie folgt:
Paket com.johnfnash.learn.domain; import Java.io.Serializable; öffentliche Klasse ViewInfo implementiert serialisierbar {private statische endgültige lange Serialversionuid = -6347911007178390219l; private userInfo userInfo; private Adressadresse; public viewInfo () {} public viewInfo (userInfo userInfo) {address address = new address (); this.userinfo = userInfo; this.address = Adresse; } public viewInfo (Adressadresse) {userInfo userInfo = new UserInfo (); this.userinfo = userInfo; this.address = Adresse; } public viewInfo (userInfo userInfo, Adressadresse) {this.userInfo = userInfo; this.address = Adresse; } // Getter, Setter} 2. adressRepository.java
Paket com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jparepository; com.johnfnash.learn.domain.address;
Testcode
Paket com.johnfnash.learn; import Java.util.list; import org.junit.after; import org.junit.befor; import org.junit.test; import org.junit.runner org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4.springrunner; Import com.johnfnash.learn.domain.address; com.johnfnash.learn.domain.ViewInfo;import com.johnfnash.learn.repository.AddressRepository;import com.johnfnash.learn.repository.UserInfoRepository;@RunWith(SpringRunner.class)@SpringBootTestpublic class UserInfoRepositoryTests { @Autowired private UserInforePository userInforePository; @Autowired private addressRepository addressRepository; @Before public void init () {Adresse adDr1 = new address ("027", "cn", "hubei", "wuhan", "wuchang", "123 street"); Adresse addr2 = neue Adresse ("023", "CN", "Chongqing", "Chongqing", "Yubei", "123 Road"); adressRepository.save (addr1); adressRepository.save (addr2); UserInfo user1 = new userInfo ("zs", 21, "männlich", "[email protected]", adDr1.getaddressId ()); UserInfo user2 = new userInfo ("ww", 25, "männlich", "[email protected]", addr2.getAddressId ()); userInforePository.save (user1); userInforePository.save (user2); } @After public void deleteAll () {userInforePository.DeletAll (); addressRepository.DeletAll (); } @Test public void testQuery () {list <ViewInfo> viewInfos = userInforePository.findViewInfo (); für (viewInfo viewInfo: viewInfos) {System.out.println (viewInfo.getUserinfo ()); System.out.println (viewInfo.getAddress ()); }}}Die abfragebezogene SQL lautet wie folgt:
Hibernate: Wählen Sie userInfo0_.user_id as col_0_0_, adresz. userinfo0_.address_id as address_2_4_0_, userinfo0_.age as age3_4_0_, userinfo0_.email as email4_4_0_, userinfo0_.name as name5_4_0_, userinfo0_.sex as sex6_4_0_ from tb_user userinfo0_ where userInfo0_.user_id =? detail_a6_3_0_, addres0_.province als provinz7_3_0_ aus tb_address address0_ wob userInfo0_.email als E -Mail4_4_0_, userInfo0_.name als Name5_4_0_, userInfo0_.sex als sex6_4_0_ aus tb_user userInfo0_ousInfo0_.user_id =? Area2_3_0_, Adresse0_.AREA_CODE AS AREE_COD3_0_, address0_. adress0_.address_id =? hibernate: Wählen Sie userInfo0_.user_id als user_id1_4_, userInfo0_.address_id als addres_2_4_, userInfo0_.age ASAGE3_4_, userinfo0_.email as. sex6_4_ from tb_user userinfo0_Hibernate: select address0_.address_id as address_1_3_, address0_.area as area2_3_, address0_.area_code as area_cod3_3_, address0_.city as city4_3_, address0_.country as country5_3_, address0_.detail_address as detail_a6_3_, addres0_.province als provinz7_3_ aus TB_ADdress address0_
Die Abfrageergebnisse sind wie folgt:
UserInfo [userId = 1, name = zs, ay 21, sex = male, E [email protected]]
Adresse [adressId = 1, aatencode = 027, Land = CN, Provinz = Hubei, Stadt = Wuhan, Gebiet = Wuchang, DetailAddress = 123 Straße]
UserInfo [userID = 2, name = ww, ay 25, sex = male, E [email protected]]
Adresse [adressId = 2, aatencode = 023, Land = CN, Provinz = Chongqing, Stadt = Chongqing, Fläche = Yubei, DetailAddress = 123 Straße]
2. Viele zu viele Kartierungen
Entitätsautor: Autor.
Entitätsbuch: Bücher
Hier wird durch die Association-Tabelle viele zu viele zu viele Verbände erreicht.
Entitätsklasse
Entitätsklasse: Autor.java
Paket com.johnfnash.learn.domain; import Java.io.Serializable; Import Javax.Persistence.Entity; Import Javax.Persistence.GeneratedValue; @ID @GeneratedValue Private Integer ID; privater Zeichenfolge Name; Public Author () {Super (); } Public Author (String -Name) {Super (); this.name = name; } // Getter, setzter @Override public String toString () {return string.format ("Autor [id =%s, name =%s]", id, name); }} Book.java Entity Klasse
Paket com.johnfnash.learn.domain; import Java.io.Serializable; Import Javax.Persistence.Entity; Import Javax.Persistence.generatedValue; Import Javax.Persistence.id; -2470510857424220408L; @ID @GeneratedValue Private Integer ID; privater Zeichenfolge Name; public book () {super (); } public book (String name) {super (); this.name = name; } // Getter, setzter @Override public String toString () {return string.format ("buchen [id =%s, name =%s]", id, name); }} Entity Class BookAuthor.java
Paket com.johnfnash.learn.domain; import Javax.Persistence.Entity; Import Javax.Persistence.id; Import Javax.Persistence.IdClass; Javax.Persistence.table;@enttity@idclass (bookAuthorpk.class) @Table (name = "book_author") bookGer | @ID Private Ganzzahlautor; public bookAuthor () {super (); } public bookAuthor (Integer bookId, Integer Authorid) {Super (); this.bookid = bookId; this.Authorid = Authorid; } // Getter, Setter}HINWEIS: Hier verwenden wir die @IDClass -Annotation, um eine Primärschlüsselklasse der Gewerkschaft anzugeben, um mehrere Eigenschaften der Entitätsklasse zuzuordnen. Der Code für diese gemeinsame Primärschlüsselklasse lautet wie folgt:
Paket com.johnfnash.learn.domain; Import Java.io.Serializable; öffentliche Klasse bookAuthorpk implementiert serialisierbar {private statische lange Serialversionuid = -1158141803682305656l; Private Ganzzahl bookId; Private Ganzzahlautor; public Integer getbookid () {return bookId; } public void setbookId (Integer bookId) {this.bookid = bookId; } public Integer getAuthorid () {return Authorid; } public void setAuthorid (Ganzzahlautor) {this.Authorid = Authorid; }} DAO -Schicht
BookRepository.java
Paket com.johnfnash.learn.repository; import java.util.list; import org.springframework.data.jpa.repository.jparepository; JpaRepository<Book, Integer> { @Query(nativeQuery = true, value = "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 and a.id = ba.author_id and b.name like ?1 group by b.id, b.name") List<Object[]> findByNameContaining(String Name);} Notiz:
1) Hier gibt NativeQuery = true an, dass native SQL zum Abfragen verwendet wird (ich persönlich denke, es ist besser, native SQL für komplexe Abfragen zu verwenden.
2) Hier wird die integrierte Funktion Group_Concat von MySQL für die Umwandlung von Zeilen zu Säulen verwendet, und HQL kann nicht direkt erkannt werden. Verursacht durch: org.hibernate.QueryException: Kein Datentyp für Knoten: org.hibernate.hql.internal.ast.tree.Methodnode -Fehler kann auftreten
Jarepository.java
Paket com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jparepository; com.johnfnash.learn.domain.author; public interface authorpository erweitert JParepository, Intereger> {{} {{} {{} {{} BookAuthorpository.java
Paket com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jparepository; import com.johnfnash.learn.domain.bookaThor; public interface bookAuthorpository erweitert JPREPSORY <bookauthor, Integer> {} {} Testcode
Paket com.johnfnash.learn; importieren statische org.junit.assert.assertequals; import Java.util.list; import org.junit.after; import org.junit.before; org.junit.test; import org.junit.runner org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4.springrunner; import com.johnash.doma. com.johnfnash.learn.domain.book; import com.johnfnash.learn.domain.bookauthor; import com.johnfnash.learn.repository.Authorrepository; import com.johnfnash.learn.repository.bookauthorrepository; com.johnfnash.learn.repository.bookrepository; @runwith (springrunner.class) @springboottestpublic class bookRepositoryTests {@autowired private bookRepository bookRepository; @Autowired Private AuthorRepository AuthorRepository; @Autowired Private bookAuthorrepository bookAuthorrepository; @Before public void init () {Autor Lewis = neuer Autor ("Lewis"); Autor Mark = neuer Autor ("mark"); Autor Peter = neuer Autor ("Peter"); authorrepository.save (Lewis); authorrepository.save (mark); authorrepository.save (Peter); Buch Spring = neues Buch ("Spring in Action"); Book Springboot = neues Buch ("Spring Boot in Action"); bookRepository.save (Frühling); bookRepository.save (Springboot); bookAuthorrepository.save (neuer bookAuthor (spring.getId (), lewis.getid ())); bookAuthorrepository.save (neuer bookAuthor (spring.getId (), mark.getId ())); bookAuthorrepository.save (neuer bookAuthor (springboot.getId (), mark.getId ())); bookAuthorrepository.save (neuer bookAuthor (springboot.getId (), Peter.getId ())); } @After public void deleteAll () {bookAuthorrepository.deletAll (); BookRepository.DeletAll (); Authorrepository.DeletAll (); } @Test public void findAll () {assertequals (bookRepository.findall (). Size (), 2); AssertEquals (Authorrepository.findall (). Size (), 3); Liste <Object []> books = bookRepository.findbynAMecontaining ("Spring%"); für (Object [] book: books) {for (Object Object: book) {System.out.print (Object + ","); } System.out.println (); }}}Nach der Ausführung der FindAll -Methode lautet die relevante SQL für die Abfrage wie folgt:
Hibernate: Select B.id, B.Name, Group_Concat (A.Name) als Authornname aus Buch B, Autor A, Book_author Ba, wo b.id = ba.book_id und a.id = ba.author_id und B.Name mögen? Gruppe von B.Id, B.Name
Die Ausgangsergebnisse sind wie folgt:
3652, Frühling in Aktion, Lewis, Mark,
3653, Spring Boot in Action, Mark, Peter,
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.