java - Hibernate 真的需要无参数构造函数吗?
问题描述
众所周知,Hibernate 需要无参数构造函数,但我试图删除它,令人惊讶的是一切正常。我在我的项目中使用 Spring-Boot,当我运行程序时,我收到了这条消息:
2020-09-04 00:13:24.749 INFO 12825 --- [ task-1] org.hibernate.tuple.PojoInstantiator : HHH000182: No default (no-argument) constructor for class: com.jb.couponSystem.data.entity.Coupon (class must be instantiated by Interceptor)
实例化我的类的拦截器是什么?如果我没有 args 构造函数,为什么在其他项目中 Hibernate 会抛出异常(如预期的那样)?
这是课程,我使用 Lombok @Data 来减少样板代码:
@Entity
@Data
public class Coupon {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Setter(AccessLevel.NONE)
private long id;
@Setter(AccessLevel.NONE)
@Column(nullable = false)
private String title;
@Setter(AccessLevel.NONE)
@Column(nullable = false)
private LocalDate startDate;
@Setter(AccessLevel.NONE)
@Column(nullable = false)
private LocalDate endDate;
@Setter(AccessLevel.NONE)
@Column(nullable = false)
private Category category;
private int amount;
@Setter(AccessLevel.NONE)
@Column(nullable = false)
private String description;
@Setter(AccessLevel.NONE)
@Column(nullable = false)
private double price;
@Setter(AccessLevel.NONE)
private String imageURL;
@ManyToOne
@JoinColumn(name = "company_id")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private Company company;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@ManyToMany
@JoinTable(name = "customer_coupon",
joinColumns = @JoinColumn(name = "coupon_id"),
inverseJoinColumns = @JoinColumn(name = "customer_id"),
uniqueConstraints = @UniqueConstraint(columnNames
= {"customer_id", "coupon_id"}))
private List<Customer> customers;
public Coupon(String title, LocalDate startDate, LocalDate endDate,
Category category, int amount, String description, double price, String imageURL) {
this.title = title;
this.startDate = startDate;
this.endDate = endDate;
this.category = category;
this.amount = amount;
this.description = description;
this.price = price;
this.imageURL = imageURL;
}
public boolean isOutOfStock() {
return amount <= 0;
}
}
更新:为了清楚起见,这种行为肯定与 lombok @Data 无关。即使我删除了该注释并添加了 getter 和 setter,它仍然可以使用相同的 Hibernate 消息。
这是关于这个问题的一些有趣的答案,但它假设你必须自己实现拦截器——我没有做。也许 Spring-Boot 本身在创建会话工厂时传递了一个已经实现的拦截器?
解决方案
推荐阅读
- python-3.x - 在 numpy 数组中查找唯一行
- swift - 如何在仅手表应用中启用 Healthkit
- c - 反向waitforsingleobject存在吗?
- typescript - “提交”事件侦听器生成的事件有哪些类型?
- git - Azure DevOps - 将主分支与过去的主分支进行比较
- python - 如何使用solve_ivp通过精确点?
- c# - Microsoft Dynamics CRM EasyRePro 自动化测试 Selenium 错误 - ElementClickInterceptedException
- codenameone - RuntimeException - 19 处的第二个字节错误
- vb.net - 一旦知道特定的变量类型,如何让 IntelliSense 更改列表成员?
- excel - 时间戳更新时 Excel 崩溃