Interview question on same name entity twice in Jpa/Hibernate

Recently when one of my friend went for an interview then interviewer trap him into an interesting question and he discussed with me, so i thought to share his experience .

Question 1 : Interviewer asked him if we can have two entity for a single table .
Answer : He said yes we can have two entity for same table name if we want to, JPA/Hibernate does not stop us from doing that .

Question 2 : Then interviewer asked him, What is DuplicateMappingException : duplicate import.
Answer : Now my friend got stuck because he does not know answer of this question . So he came too me after interview and discuss it with me . Then i told my friend that this exception occurs when we have two same name java class having @entity annotation in different package. Actually what JPA does that it gave a unique name to each entity you define with @entity annotation as defined below .


package com.google.employee;
@Entity
@Table(name="GOOGLE_EMPLOYEE")
public class Employee{
}

package com.ask.employee;
@Entity
@Table(name="ASK_EMPLOYEE")
public class Employee{
}

As we did not provide any name inside @Entity annotation so, JPA gave class name as entity name. JPA does not allow two same name entity and will give exception Entity name must be unique in a persistence unit . So if we want to have two same name classes in different package as our entity then we should provide a name as given below.


package com.google.employee;
@Entity("GoogleEmployee")
@Table(name="GOOGLE_EMPLOYEE")
public class Employee{
}

package com.ask.employee;
@Entity("AskEmployee")
@Table(name="ASK_EMPLOYEE")
public class Employee{
}

and we will use this name in named queries after from clause too.

select askEmployee from AskEmployee askEmployee where askEmployee.employeeName=:emplyeeName

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.
MQ connection not closed and giving MQ Error-2009

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s