我知道这是一个常见问题,但我还没有找到另一个解决我的疑惑。永久模型到域模型映射而不暴露域对象属性
通常,如果项目很小,我会在表示域对象的同一个对象中使用持久性注释。这允许从数据库加载实体并使所有设置器保持私密,确保任何实例始终处于有效状态。就像:
@Entity
class SomeEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String attribute1;
private String attribute2;
private String attribute3;
// ... other attributes
protected SomeEntity() {}
/* Public getters */
public Long getId() { ... }
public String getAttribute1() { ... }
public String getAttribute2() { ... }
/* Expose some behaviour */
public void updateAttributes(String attribute1, String attribute2) {
/* do some validations before updating */
}
}
我的问题出现,如果我想hava不同的持久性模型。然后我会碰到这样的:
/* SomeEntity without persistent info */
class SomeEntity {
private Long id;
private String attribute1;
private String attribute2;
private String attribute3;
// ... other attributes
protected SomeEntity() {}
/* Public getters */
public Long getId() { ... }
public String getAttribute1() { ... }
public String getAttribute2() { ... }
/* Expose some behaviour */
public void updateAttributes(String attribute1, String attribute2) {
/* do some validations before updating */
}
}
和DAO:
@Entity
class SomeEntityDAO {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String attribute1;
private String attribute2;
private String attribute3;
public SomeEntityDAO() {}
/* All getters and setters */
}
我的问题是,我怎么能映射到SomeEntityDAO不SomeEntity暴露SomeEntity的属性?
如果我创建了一个构造函数,例如:public SomeEntity(String attribute1, String attribute2, ...) {}
,那么任何人都可以创建SomeEntity的无效实例。如果我在SomeEntity中公开所有setter,则会发生同样的情况。
我也不认为是一个有效的解决方案使用updateAttributes()
构建对象,因为这将执行一些验证我不想在此时执行(我们相信存在于数据库中的数据)。
我在考虑让所有的setter受到保护,所以DAO可以扩展实体并有权访问setters ......但我不确定这是否是一个好选择。
哪种解决此问题的最佳或常用方法?
你想要一个ORM,它允许没有setter或有私人setter的实体类? –
我指的是域模型类而不暴露公共设置者。只公开行为方法。吸气者很好。 ORM类可以有getter和getters。 –