Bilbo Baggins
Bilbo Baggins

Reputation: 3019

As per JPA spec, default constructor is must in entity classes, why?

I have a question, As I have mentioned above, I know as per JPA spec and Hibernate doc, the default constructor is must and should have package level access. I would like to know that without the public constructor it the code still works. Why?

I also got into the code of Class.java I found a line as below

// No cached value available; request value from VM

Does this means that it requests a constructor from VM? i.e. the default constructor. Does this mean that my code(without default constructor) is VM dependent? What about byte code enhancement?

My Refactored Question:

I want to know why JPA has added this a "MUST" requirement to define a default constructor for an entity.

As per the spec:

The entity class must have a no-arg constructor. The entity class may have other constructors as well.
The no-arg constructor must be public or protected.

Why so? I know that Java does introduces a default constructor if one is not defined, then why to put this in spec?

I hope I have placed my question correctly this time.

Thanks Again... :)

Upvotes: 1

Views: 1528

Answers (1)

geert3
geert3

Reputation: 7351

In Java if you define no constructors at all, you'll get a default constructor, which is public and zero-args, i.e. it meets the requirements of the JPA spec.

But if you do define any other constructors, the default constructor is not added automatically, and so the class doesn't meet the JPA requirements. You'd have to add the zero-arg constructor explicitly, next to any other constructors you would want.

As to why the JPA spec needs it: it needs a zero-arg constructor as it wouldn't know what values to pass to the parameters in other constructors.

nb: the stuff you mention about Class.java is totally unrelated

Upvotes: 1

Related Questions