6

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

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

and:

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

I was creating a search query with: .getSimpleName() but it didn't work because their simple name are the same. I changed it to .getName().

However, it still confuses to which User to return.

EDIT:

I have that:

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 makes something like:

Select p from User p Where p.name=?

It is still User and it doesn't include package information and returns me wrong User class.

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82
kamaci
  • 72,915
  • 69
  • 228
  • 366

1 Answers1

5

If you want to create a JPQL query you need to pass the Entity name to it. As you posted, you have 2 entities which are represented by the same Java class, but different Entity name (X_USER explicitly set by you and User set implicitly).

If you want to get dynamically the name of the entity you should rather use the Metamodel, so something like this should do the work (not checked):

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

HTH.

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82