Issue
I am trying to set up a database table using a JpaRepository. I have the following model class:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Data
@Entity
@Table
public class MyModel {
@Id
@GeneratedValue
private final int id;
private final String name;
private final String imagePath;
}
When I run my application the table is created just fine. I have manually added a row to the table, yet when I try to look up the row using repository.findById
I get the following error:
org.hibernate.InstantiationException: No default constructor for entity: : com.mypackage.mypackage.model.MyModel
I am confused by the 'no default constructor' error. I thought the @Data
annotation automatically created a constructor for the class?
Solution
Hibernates doesn't play with with immutable entities, it wants:
- a nullary constructor:
public MyModel() {}
- getters and setters
So just remove the final
modifiers so that @Data
generates all this for you.
Ah, that's why it rings a bell, it relates to that other question of yours. So yeah, with Hibernate entities, you can't easily use immutable entities. You can still add @AllArgsConstructor
alongside @Data
if you need such a constructor too.
Edit: As rightfully raised by Andrey B. Panfilov in the comments, @Data
shouldn't be used at all on top of entities. Quoting Thorben Janssen:
The bottom line is that you can use the
@Getter
,@Setter
, and@Builder
annotation without breaking your application. The only Lombok annotations you need to avoid are@Data
,@ToString
, and@EqualsAndHashCode
.
Answered By - sp00m
Answer Checked By - Mary Flores (JavaFixing Volunteer)