Sandeep
Sandeep

Reputation: 1401

Constructor for Hibernate Entity class

In my domain Entity class I have an attribute that I want to use as the primary key (GenerationType.AUTO) {for use with the JPA Criteria API}. I would like to define a constructor for this Entity class, which will initialize all attributes, except the primary key attribute, since Hibernate will provide this value.

In other words, the constructor will leave the Primary Key attribute undefined. Personally I don’t see any issues, but I want to get this approach vetted by the experts.

Question

Upvotes: 1

Views: 717

Answers (2)

MWiesner
MWiesner

Reputation: 9043

The JPA specification document (version 2.2) holds the answer in Section 2.4, page 31:

The value of its primary key uniquely identifies an entity instance within a persistence context and to EntityManager operations as described in Chapter 3, “Entity Operations”. The application must not change the value of the primary key [10]. The behavior is undefined if this occurs.

[10] This includes not changing the value of a mutable type that is primary key or an attribute of a composite primary key.

Therefore, using a constructor to initialize or set the value of a primary key may not a good idea as "undefined behavior" might result from it.

Keep in mind that - by the JPA spec - a no-arg constructor must also be provided in each entity class with a custom constructor (as described in your question). Search the specification for "constructor" for further details, especially Section 2.1.

IMHO, this should guide you in making a good design choice.

Hope this helps.

Upvotes: 2

SternK
SternK

Reputation: 13041

According to this

The entity class must have a public or protected no-argument constructor. It may define additional constructors as well.

and further

JPA requires that this constructor be defined as public or protected. Hibernate, for the most part, does not care about the constructor visibility, as long as the system SecurityManager allows overriding the visibility setting. That said, the constructor should be defined with at least package visibility if you wish to leverage runtime proxy generation.

But look also at this. It is useful sometimes to have an entity id among of constructor arguments.

Upvotes: 1

Related Questions