问题
I have a database with 4 tables:
company,staff,department,project
Company.java
@Entity
@Table(name = "company")
@SqlResultSetMapping(name = "COMPANY", entities =
{
@EntityResult(entityClass = Company.class),
@EntityResult(entityClass = Staff.class)
})
...
GetEntity.java
EntityManagerFactory emf = Persistence.createEntityManagerFactory("GetEntityPU");
EntityManager em = emf.createEntityManager();
String query = "SELECT *
FROM company c
JOIN staff s
ON c.ID = s.companyID";
Query q = em.createNativeQuery(query, "COMPANY");
List<Object[]> list = q.getResultList();
From above code, I can retrieve all data from Company entity and Staff entity.
Now I want to retrieve all data from any 2 tables:
maybe all data for company, staff tables OR all data for staff, department tables
How should I control every entity in my query?
I really no ideas on how to do it.
Any ideas or useful source link are welcome.
回答1:
Mapping query to a bean could help you, check this out: query to bean
来源:https://stackoverflow.com/questions/30217569/jpa-native-query-retrieve-multiple-entities