我可以制定以下策略。
当您不想获取整个集合或使用某些附加条件进行获取时,此策略非常有效,您可以使用命名查询检索它(集合关系)。对多对多关系的 JOIN 表使用单独的 DAO 进行 CRUD 操作,例如,用户可以有多个帐户,并且帐户可以由多个用户共享。为所有三个表创建域模型/ DAO,使用关系映射进行检索,DDL 使用单个属性。
@Entity
@Table(name="account" )
public class Account {
@Id (name="accountid")
private Long accountId;
@Column
private String type;
// removed @OneToMany as it causes issue while serializing to xml
@Transient
private Collection accountUsers;
//rest of the properties n geter setter goes here
}
@Entity
@Table(name="user")
public class User {
@Id(name="userid")
private Long userId;
@Column
private String name;
// by making transient jpa / hibernate does not initialize it with proxy.. so it remains null
/* you can populate this property using named query whenever required .*/
@Transient
private Collection userAccounts;
// rest of the properties n getter setter goes here
}
@Entity
@Table(name="AccountUser")
public class AccountUser {
// whatever your strategy to implement primary key here ,
@Id (name="accountuserid")
private Long accountUserId;
/* please note this annotation , made insertable/updatable false , relation defined just for fetching relation
*/
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "accountid", referencedColumnName = "accountid", insertable = false, updatable = false)
private Account account;
// look at insertable / updatable properties its turned off
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "userid", referencedColumnName = "userid", insertable = false, updatable = false)
private User user;
//
@Column ( name = "userid" )
private Long userId;
@Column ( name = "accountid" )
private Long accountId;
@Column ( name="opendate")
private Date opendate;
}
/* use separate dao to save above beans */
// somthing like this
public class AccountDAOImpl extends GenericDAOImpl implements AccountDAO {
}
public class UserDAOImpl extends GenericDAOImpl implements UserDAO {
}
public class AccountUserDAOImpl extends GenericDAOImpl implements AccountUserDAO {
}
我试图解释是否需要任何澄清,请回复。谢谢