简体   繁体   中英

Joining two tables in JPA when the entities does not have relation mapping between them

I have a User entity and a Pet entity. There are no @OneToMany, @ManyToMany or other between the User and the Pet. The reason is that each user may have thousands of pets (at least in this example). Since I don't want to eager load it (too slow) and I don't want to lazy load (cause lazy initialization exception...and I don't want to use open in view filter) I have created methods in the user repository that have a name like this (the reason is that I want to have the opportunity to return only subsets of the relational properties. I don't want all the pets of a user:

getPetsForUser(final User user){...} . The examples of joins I have seen in JPA obviously uses the relational property on the entities it seems. How do I do this in JPA?

In SQL I would just use the foreign key...

You'll have to explicitly use the foreign key, probably by extracting it from the User object ( User.getId() , I presume) and then using it as a raw long or equivalent field on the Pet --with no foreign-key integrity, cascades, or query-based joins.

You might be better off reexamining why getting lazy-loading working is such a bad thing, and if JPA is the right approach.

JPQL only works on mapped entity and mapped relationships.
One way is to use native SQL query and manage result as List<Object[]> .
Else you can unwrap EntityManager to obtain a Hibernate Session and mappign result with SQLQuery.setResultTransformer(new AliasToBeanResultTransformer(Pet.class)) .
For example:

List<Pet> getPetsForUser(final User user) {
    Session s = entityManager.unwrap(Session.class);
    List<Pet> pets = s.createSQLQuery("select * from PETS p inner join USERS u on (p.user_id = u.id) where u.id = :id").setParameter("id",user.getUserID()).setResultTransformer(new AliasToBeanResultTransformer(Pet.class)).list();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM