Search code examples
javahibernatejpaeclipselinkentitymanager

Entity class must have non argumented constructor


I am studying JPA, so while studying on a JPA BLOG Vogella 1.2 Entity Heading, i came across a line which says:

All entity classes must define a primary key, must have a non-arg constructor and or not allowed to be final

I am not able to understand this line. Do we need to specifically write a non-argumented constructor, because a default non argumented constructor is always inherited by classes.

what do they mean by not allowing to be final, do this mean we can always extend an Entity class? If so why is this compulsion, why it can not be final


Solution

  • By default, you get non arg constructor when there is no constructor defined in your class which has nothing to do with JPA. Yes if you are defining a constructor, then you have to define no arg constructor like:

     public class Student {
          public Student() {}//default ctor which is needed by JPA to convert row from DB to java object
          public Student(int id) {..}//ctor which accepts one arg
     }
    

    Making class final meaning you can't subclass. JPA vendor's like Hibernate creates proxy to lazily fetch rows which will ultimately limit your options for performance tuning. Hence you see that your class may/may not be final depending on your use case.