Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JPA require a no-arg constructor for domain objects?

Why does JPA require a no-arg constructor for domain objects? I am using eclipselink and just got this exception during deployment.

Exception [EclipseLink-63] (Eclipse Persistence Services-1.1.0.r3639-SNAPSHOT): 
org.eclipse.persistence.exceptions.DescriptorException

Exception Description: The instance creation method   
[com.me.model.UserVO.<Default Constructor>], with no parameters, 
  does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: 
  com.me.model.UserVO.<init>()
Descriptor: RelationalDescriptor(com.me.model.UserVO --> 
  [DatabaseTable(user)])
like image 621
Jacques René Mesrine Avatar asked May 11 '10 07:05

Jacques René Mesrine


People also ask

Why do we need no-argument constructor in spring boot?

The arguments of a constructor can only be found by type, not by name, so there is no way for the framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.

What will happen if we don't have no args constructor in Entity Bean?

So if you won't have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get `HibernateException`.

Why are there no args constructors?

1. No-argument constructor: A constructor that has no parameter is known as the default constructor. If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class.

Does JPA entity need constructor?

The JPA Specification provides its own set of restrictions, here are the two most important to us: 1. The entity class must have a no-arg constructor. The entity class may have other constructors as well.


2 Answers

Because it often happens that the JPA provider has to instantiate your domain object dynamically. It cannot do so, unless there is a no-arg constructor - it can't guess what the arguments should be.

like image 106
Bozho Avatar answered Oct 15 '22 19:10

Bozho


Also notice that this is not provider dependent. It is a JPA specification.

JPA v2.0 JSR-317 and v2.1 JSR-338 says:

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.

like image 27
José Andias Avatar answered Oct 15 '22 17:10

José Andias