I could work out with following strategy.
This strategy works very well when you dont want fetch whole collection , or fetch with some addition criteria,
, you may retrieve it(collection relation) with named query.
use separate DAO for CRUD operation on JOIN table of many to many relation
e.g.
User can have many accounts and account can be shared by many users.
create domain models/ DAO for all the three tables,
use relation mapping for just retrieval and for DDL use individual properties.
@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 {
}
I tried to explain if need any clarification kindly revert back. thanks