Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the 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 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.

like image 799
kamaci Avatar asked Nov 17 '11 13:11

kamaci


People also ask

Can two classes in different packages have the same name?

Yes, you can have two classes with the same name in multiple packages. However, you can't import both classes in the same file using two import statements. You'll have to fully qualify one of the class names if you really need to reference both of them.

Can 2 classes have same name in Java?

For convenience, Java allows you to write more than one method in the same class definition with the same name. For example, you can have two methods in ShoppingCart class named computeCost. Having two or more methods named the same in the same class is called overloading.

Is JPA between inclusive?

The BETWEEN operator can be used in conditional expressions to determine whether the result of an expression falls within an inclusive range of values. Numeric, string, and date expressions can be evaluated in this way.

What is the difference between HQL and JPQL?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.


1 Answers

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.

like image 184
Piotr Nowicki Avatar answered Oct 15 '22 03:10

Piotr Nowicki