Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

jpa - Java entity - why do I need an empty constructor?

This might sound stupid to you, but why do I need to define an empty constructor in my @Entitys?

Every tutorial I saw said : every entity needs an empty constructor.

But Java always give you a default invisible empty constructor (if you don't redefine one).

Let me clarify.. What I understood by "need" was write.

Meaning: always write an empty constructor in your entity.

example:

@Entity
public class MyEntity implements Serializable {

   @Id
   private String str;

   public MyEntity(){}

   //here getter and setter
}

But Java always gives you this empty constructor when you don't redefine it (write an other one with parameters).

In this case writing this empty constructor seems useless.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

An empty constructor is needed to create a new instance via reflection by your persistence framework. If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default.

You can also use the @PersistenceConstructor annotation which looks like following

@PersistenceConstructor
public Movie(Long id) {
    this.id = id;
}

to initialise your entity if Spring Data is present in your project. Thus you can avoid the empty constructor as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...