How can JPA recognize two classes with the same name, but in different packages?

I use JPA and Hibernate for my project. I have two classes with the same names , but in different packages . It:

@Entity(name = "X_USER") @Table(name = "X_USER") public class User { 

and

 @Entity @Table(name="Y_USER") public class User { 

I created a search query using .getSimpleName() , but this did not work because their simple name is the same. I changed it to .getName() .

However, it still confuses which User to return to.

EDIT:

I have:

 SELECT_BY_PROPERTY_QUERY = "SELECT p FROM :CLASS: p WHERE p.:PROPNAME:=?"; 

and I that:

 SELECT_BY_PROPERTY_QUERY.replaceFirst(":CLASS:", clazz.getName()).replaceFirst(":PROPNAME:", propertyName); 

and when I debug it, it does something like:

 Select p from User p Where p.name=? 

It is still User and does not include package information and returns the wrong User class to me.

+6
source share
1 answer

If you want to create a JPQL query, you need to pass the name of the entity . As you publish, you have 2 objects that are represented by the same Java class, but with a different Entity name ( X_USER explicitly set by you and User set implicitly).

If you want to dynamically determine the name of an object, you should use the Metamodel , so something like this should do the job (not verified):

 EntityManager em = ... Metamodel model = em.getEntityManagerFactory().getMetamodel(); String entityName = model.entity(com.your.pckg.User.class).getName(); 

NTN.

+4
source

Source: https://habr.com/ru/post/901716/


All Articles