Home > Back-end > Jpa how to customize the query one-to-many mapping
Jpa how to customize the query one-to-many mapping
Time:09-27
If there are so three entities User, the Orders, roles, the relationship between the following The User and the Orders are a one-to-many relationship between User and Role is a one-to-many relationship between The following entity content
The class User { private Long id; private String name; Private XXX;//other properties no longer list
The @onetomany (mappedBy="user") Private Set The orders;
The @onetomany (mappedBy="user") Private Set Roles;
}
The class the Orders { private Long id; Private String order_num; Private XXX;//other properties no longer list
@ ManyToOne @ JoinColumn (name="userId") private User user;
}
The class Roles { private Long id; private String name; private String desc; Private XXX;//other properties no longer list
@ ManyToOne @ JoinColumn (name="userId") private User user;
}
When I want to custom query certain fields you can use the following SQL (SQL="select id, name from the Users where XXX"), but check out the entity does not contain Set The figures,
so the question comes, how do I custom query a one-to-many relationship of entities, such as: execute the query the User entity id, name, Set These attributes, instead of a cascade query Role this table, mapping and the User entity how to query, namely query results is a List In the User id, name, and collections Set
CodePudding user response:
You can use a JPQL + vo, is roughly such
Select new UserOrderVo (u.i d, u.n ame, u.o. rders) from user u.
If need to add a UserOrderVo constructor, parameter type is the structure of the above types