我有一个适合建造者模式的类,其中有很多参数,我不想使用大量的构造函数。但我的问题是这个类是一个JPA实体,这对我来说很新颖。由于私有数据成员在构造函数中没有初始化,因此出现了错误,而据我所知,JPA需要一个空的受保护构造函数。请问有谁能帮忙解决吗?如果能提供一个示例就更好了。下面是代码的基本示例,但它非常通用,为了节省时间和空间,我省略了许多访问器和数据成员。
@Entity//(name= "TABLE_NAME") //name of the entity / table name
public class Bean implements Serializable {
private static final long serialVersionUID = 1L;
@Id //primary key
@GeneratedValue
Long id;
private final DateTime date;
private final String title;
private final String intro;
//used by jpa
protected Bean(){}
private Bean(Bean Builder beanBuilder){
this.date = beanBuilder;
this.title = beanBuilder;
this.intro = beanBuilder;
}
public DateTime getDate() {
return date;
}
public String getTitle() {
return title;
}
public static class BeanBuilder Builder{
private final DateTime date;
private final String title;
//private optional
public BeanBuilder(DateTime date, String title) {
this.date = date;
this.title = title;
}
public BeanBuilder intro(String intro){
this.intro = intro;
return this;
}
public BeanBuilder solution(String solution){
this.intro = solution;
return this;
}
public Bean buildBean(){
return new Bean(this);
}
}
}
final
的内容。也许可以参考 https://dev59.com/DWUo5IYBdhLWcg3w7jIq 或 https://en.wikipedia.org/wiki/Final_(Java)。 - user180100