Существует два метода реализации для многоточного запроса в Spring Data JPA. Первое - использовать каскадный запрос Hibernate для его реализации, а второе - создать интерфейс набора результатов для получения результатов после подключенного табличного запроса. Вот второй метод.
1. Один-один картирование
Entity UserInfo: Пользователь.
Адрес организации: домашний адрес.
Здесь ассоциация «один к одному» достигается с помощью метода внешнего ключа (одна сущность связана с первичным ключом другого объекта через внешний ключ).
Класс сущности
1. Entity Class UserInfo.java
Пакет com.johnfnash.learn.domain; import java.io.serializable; импорт javax.persistence.entity; import javax.persistence.generatedValue; импорт javax.persistence.generationtype; импорт javax.persistence.id; импорт javax.persistence.table@antity@antity@antity@antity@antity@antity@antity@antity@antity. UserInfo реализует Serializable {Private Static Long Long SerialVersionUID = 8283950216116626180L; @ID @GeneratedValue (стратегия = GenerationType.Identity) Private Long UserId; Приватное название строки; частный int возраст; частный строковый секс; Приватная строковая электронная почта; // Ассоциация с адресом частного длинного адреса; public userinfo () {super (); } public userInfo (имя строки, int age, строковая секс, строка электронная почта, long addressId) {super (); this.name = name; this.age = возраст; this.sex = sex; this.email = электронная почта; this.addressid = addressid; } // getter, setter @Override public String toString () {return string.format ("userInfo [userId =%d, name =%s, возраст =%s, sex =%s, email =%s]", userId, имя, возраст, пол, электронная почта); }} 2. Адрес класса сущности. Java
Пакет com.johnfnash.learn.domain; import javax.persistence.entity; import javax.persistence.generatedValue; import javax.persistence.generationtype; импорт javax.persistence.id; импорт javax.persistence.table;@entity@table (name = "tb_address") address ") @GeneratedValue (стратегия = GenerationType.Identity) private Long AddersID; частная строковая зона; частная строковая страна; частная строковая провинция; частный строковый город; частная струнная зона; частная строка DefitAddress; public Adder () {super (); } public address (строковая область, строковая страна, провинция String, String City, String Area, String DetailDress) {super (); this.areacode = gain -код; this.country = страна; this.province = провинция; this.city = city; this.area = область; this.detailAddress = deftainAddress; } // getter, setter @Override public String toString () {return "Address [addressId =" + addressID + ", geablecode =" + areacode + ", country =" + country + ", province =" + province + ", city =" + city + ", area =" + reable + ", detailAddress =" + defitaiddress + "]"; }} Дао слой
1. userinforepository.java
пакет com.johnfnash.learn.repository; import java.util.list; import org.springframework.data.jpa.repository.jparepository; import org.springframework.data.jpa.repository.query; importm.johnfnash.learn.domain.userinfo com.johnfnash.learn.domain.viewinfo; public user userinforePository расширяет jParePository <userInfo, long> {@Query (value = «Выберите новый com.johnfnash.learn.domain.viewinfo (u, a) из userinfo u, адрес u.addressid = a.addressid weportiin findViewInfo ();} ПРИМЕЧАНИЕ. Класс ViewInfo здесь используется для получения множественных наборов результатов запросов (используя новый конструктор имени класса.
Код заключается в следующем:
пакет com.johnfnash.learn.domain; import java.io.serializable; открытый класс ViewInfo реализует сериализуемые {частный статический конечный длинный последовательный Private UserInfo userInfo; Частный адрес адреса; public viewInfo () {} public viewInfo (userInfo userInfo) {адрес Адрес = новый адрес (); this.userinfo = userInfo; this.address = адрес; } public viewInfo (адрес адрес) {userInfo userInfo = new userInfo (); this.userinfo = userInfo; this.address = адрес; } public viewInfo (userInfo userInfo, адрес адрес) {this.UserInfo = userInfo; this.address = адрес; } // getter, setter} 2. AddressRepository.java
Пакет com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jparepository; import com.johnfnash.learn.domain.address; public addrestrestory addressitory jparepository <, long> {} Тестовый код
пакет com.johnfnash.learn; импорт java.util.list; import org.junit.after; import org.junit.before; import org.junit.test; импорт org.junit.runner.runwith; import org.springframework.beans.factory.annotation.AutowiTire; org.springframework.boot.test.context.springboottest; import org.springframework.test.context.junit4.springrunner; импорт com.johnfnash.learn.domain.address; импорт com.johnfnash.learn.domain.userinfo; com.johnfnash.learn.domain.viewinfo; import com.johnfnash.learn.repository.addressrepository; import com.johnfnash.learn.repository.userinforePository; @runwith (Springrunner.class) @springbootstestpublic userinforepostory @springboottestpublic Userinforepository userinforePository; @Autowired Private AddrestRepository AddressRepository; @Before public void init () {адрес addr1 = новый адрес ("027", "cn", "hubei", "wuhan", "wuchang", "123 Street"); Адрес addr2 = новый адрес («023», «CN», «Чунцин», «Чунцин», «Yubei», «123 Road»); addressrepository.save (addr1); addressrepository.save (addr2); UserInfo user1 = new userInfo ("zs", 21, "Male", "[email protected]", addr1.getAddressId ()); UserInfo user2 = new userInfo ("ww", 25, "мужчина", "[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 (); для (viewInfo viewInfo: viewInfos) {System.out.println (viewInfo.getUserInfo ()); System.out.println (viewInfo.getAddress ()); }}}Связанный с запросом SQL выглядит следующим образом:
Hibernate: select userinfo0_.user_id as col_0_0_, address1_.address_id as col_1_0_ from tb_user userinfo0_ cross join tb_address address1_ where userinfo0_.address_id=address1_.address_idHibernate: select userinfo0_.user_id as user_id1_4_0_, userInfo0_.address_id as address_2_4_0_, userinfo0_.age as age3_4_0_, userinfo0_.email as emike4_4_0_, userinfo0_.name as name5_4_0_, userinfo0_.sex as sex6_0_0_ от tb_user userInfo0_. userInfo0_.user_id =? Hibernate: SELECT ADDRICE0_.Address_id AS ADDRES_1_3_0_, ADDRES0_.Area AS AS AREA2_3_0_, ADDRES0_.AREA_CODE AS ASER_COD3_3_0_0_. detail_a6_3_0_, адресат 0_. userInfo0_.email как email4_4_0_, userInfo0_.name as name5_4_0_, userInfo0_.sex as sex6_4_0_ из tb_user userinfo0_ где userInfo0_.user_id =? область 2_3_0_, адресат 0_.erea_code as aever_cod3_3_0_, адресат 0,.city as as City4_3_0_, адресат 0_.country As Country5_3_0_, Adder0_.detail_Addres address0_.address_id =? Hibernate: Select userInfo0_.user_id as user_id1_4_, userInfo0_.address_id as Adder_2_4_, userInfo0_.age as age3_4_, userInfo0_.email as email4_4_, userInfo0_.name asme_, asm_, asmesexx assexxex. sex6_4_ из tb_user userinfo0_hibernate: select address0_.address_id as address_1_3_, address0_.area as aeam2_3_, address0_.area_code as aever_cod3_3_, address0_.city as City4_3_, Address0_.countr Address0_.province As Province7_3_ из TB_ADDRESS ADDRED0_
Результаты запроса следующие:
UserInfo [userId = 1, name = zs, возраст = 21, пол = мужчина, электронная почта[email protected]]
Адрес [addressId = 1, geablecode = 027, country = cn, province = hubei, city = wuhan, area = wuchang, detailddress = 123 Street]
UserInfo [userId = 2, name = ww, age = 25, sex = мужчина, электронная почта[email protected]]
Адрес [addressId = 2, geaincode = 023, country = cn, province = chongqing, city = chongqing, aem = yubei, detailddress = 123 дорога]
2. Много-много-картирование
Автор организации: автор.
Книга сущности: книги
Здесь ассоциация многих ко многим достигается за счет таблицы ассоциаций.
Класс сущности
Класс сущности: Автор. Ява
пакет com.johnfnash.learn.domain; import java.io.serializable; импорт javax.persistence.entity; import javax.persistence.generatedValue; импорт javax.persistence.id; @EntityPubbublic Puthors Pulatroms Serializable {private static final Long Serialversionuiduid = 12275587779. @ID @GeneratedValue Private Integer ID; Приватное название строки; public Author () {super (); } public Author (String name) {super (); this.name = name; } // getter, setter @Override public String toString () {return string.format ("Автор [id =%s, name =%s]", id, name); }} Book.java Entity Class
Пакет com.johnfnash.learn.domain; import java.io.serializable; импорт javax.persistence.entity; import javax.persistence.generatedValue; импорт javax.persistence.id; @entityPublic Class Replomsable Serializable {Private Final Lony Serialversionuid = = -2470510857424220408L; @ID @GeneratedValue Private Integer ID; Приватное название строки; public book () {super (); } public Book (String name) {super (); this.name = name; } // getter, setter @Override public String toString () {return string.format ("book [id =%s, name =%s]", id, name); }} Класс сущности Bookauthor.java
пакет com.johnfnash.learn.domain; импорт javax.persistence.entity; импорт javax.persistence.id; import javax.persistence.idclass; импорт javax.persistence.table;@entity@idclass (bookauthorpk.class) @table (name = "book_author") @ID Private Integer Authorid; public bookathor () {super (); } public bookatortor (Integer BookId, Integer Authorid) {super (); this.bookiD = bookId; this.authorid = Authorid; } // getter, setter}ПРИМЕЧАНИЕ. Здесь используйте аннотацию @IDClass, чтобы указать класс первичного ключа Союза, чтобы отобразить несколько свойств класса сущности. Код для этого совместного класса первичного ключа заключается в следующем:
пакет com.johnfnash.learn.domain; import java.io.serializable; открытый класс Bookauthorpk реализует сериализуемые {частный статический конечный длинное длинное последовательность = -1158141803682305656l; частная целочисленная книга; Частное целое число авторитетных; public integer getBookId () {return bookId; } public void setBookId (Integer BookId) {this.BookId = bookId; } public integer getAuthorid () {return Authorid; } public void setAuthorid (integer Authorid) {this.Authorid = Authorid; }} Дао слой
BookRepository.java
Пакет com.johnfnash.learn.repository; import java.util.list; import org.springframework.data.jpa.repository.jparepository; import org.springframework.data.jpa.Repository.query; импорт com.johnfnash.learn.domen. JparePository <book, integer> {@Query (NativeQuery = true, value = "select b.id, b.name, group_concat (a.name) как Authorname из книги B, автор A, Book_author ba" + "где B.id = ba.book_id и a.id = ba.author_id и b.name like? FindByNaMeconting (String name);} Примечание:
1) Здесь NativeQuery = true указывает, что Native SQL используется для запроса (я лично думаю, что лучше использовать Native SQL для сложных запросов.
2) Здесь встроенная функция MySQL Group_Concat используется для преобразования ряда в колонну, и HQL не может быть непосредственно распознан. Вызвано: org.hibernate.queryexception: нет типа данных для узла: org.hibernate.hql.internal.ast.tree.methodnode может возникнуть ошибка
JparePository.java
Пакет com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jparepository; import com.johnfnash.learn.domain.author;
BookAuthorRepository.java
Пакет com.johnfnash.learn.repository; import org.springframework.data.jpa.repository.jparepository; import com.johnfnash.learn.domain.bookauthor; public interface bookauthorrepository extends jparepository <bookauthor, integer> {} Тестовый код
Пакет com.johnfnash.learn; импорт статический org.junit.assert.assertequals; импорт java.util.list; import org.junit.after; импорт org.junit.fore; импорт org.junit.test; импорт org.junit.runner.runwith; org.springframework.beans.factory.annotation.autowired; import org.springframework.boot.test.context.springboottest; импорт org.springframework.test.context.junit4.springrunner; импорт com.johnfnash.learn.domain.Author; com.johnfnash.learn.domain.book; import com.johnfnash.learn.domain.bookauthor; импорт com.johnfnash.learn.repository.authorrepository; импорт com.johnfnash.learn.repository.bookauthorrepository; com.johnfnash.learn.repository.bookrepository; @runwith (springrunner.class) @springboottestpublic class bookpositorytests {@autowired private bookpository bookpository; @Autowired Private AuthorRePository AuthorRePository; @Autowired частный BookauthorRepository bookauthorRepository; @Before public void init () {автор Lewis = new Author ("Lewis"); Автор Марк = новый автор («Марк»); Автор Питер = новый автор ("Петр"); Authorrepository.save (Льюис); Authorrepository.save (Mark); AuthorRePository.save (Питер); Книга Spring = новая книга («Весна в действии»); Книга Springboot = новая книга («Spring Boot in Action»); BookRepository.save (Spring); BookRepository.save (Springboot); BookAuthorRepository.save (новый Bookauthor (Spring.getId (), Lewis.getId ())); bookauthorRepository.save (новый Bookauthor (Spring.getId (), mark.getId ())); BookAuthorRepository.save (новый Bookauthor (springboot.getid (), mark.getid ())); bookauthorrepository.save (новый 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); Список <object []> books = bookRepository.findbynameconting ("Spring%"); for (object [] book: books) {for (объект объекта: книга) {system.out.print (object + ","); } System.out.println (); }}}После выполнения метода Findall соответствующий SQL для запроса заключается в следующем:
Hibernate: Select B.Id, B.Name, Group_Concat (A.Name) как AuthorName из книги B, Автор A, Book_Author BA, где b.id = ba.book_id и a.id = ba.author_id и b.name, как? Группа B.ID, B.Name
Результаты выходных данных следующие:
3652, Весна в действии, Льюис, Марк,
3653, Spring Boot in Action, Марк, Питер,
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.