hibernate如何操作中间表
有三个表Account,department,account_department(中间表),三个表是hibernate 注解生成的,现在我要往一个部门id=3的部门中加一个用户,该如何操做呢,方法为
public Account insertAccountOnDepartment(Account account,Long departmentId){
this.save(account);//往account表中插入一条记录,例如插入的account_id为1
//但中间表中该如何插入account_id,department_id values(1,3)呢?
}
类定义大致如下:
@Entity
@Table(name = "ACCOUNTS")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Account {
private Long id;
private String loginName;
private List<Department> departments;
...
@Override
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_STORE")
@SequenceGenerator(name = "SEQ_STORE", sequenceName = "ACCOUNTS_ID", allocationSize = 2)
@Column(length = 12)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToMany(fetch = FetchType.LAZY)
@OrderBy("priority desc")
@JoinTable(name = "ACCOUNT_DEPARTMENT_ACCOUNT", joinColumns = { @JoinColumn(name = "account_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "department_id", nullable = false, updatable = false) })
@Cascade( { CascadeType.SAVE_UPDATE })
public List<Department> getDepartments() {
return departments;
}
public void setDepartments(List<Department> departments) {
this.departments = departments;
}
}
@Entity
@Table(name = "ACCOUNT_DEPARTMENTS")
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Department {
private Long id;
private List<Department> children;
private List<Account> accounts;
@Override
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_STORE")
@SequenceGenerator(name = "SEQ_STORE", sequenceName = "ACCOUNT_DEPARTMENTS_ID", allocationSize = 2)
@Column(length = 12, name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToMany(fetch = FetchType.LAZY)
@OrderBy("priority desc")
@Cascade(CascadeType.ALL)
@JoinColumn(name = "parentId")
public List<Department> getChildren() {
return children;
}
public void setChildren(List<Department> children) {
this.children = children;
}
@ManyToMany(fetch = FetchType.LAZY)
@OrderBy("priority desc")
@JoinTable(name = "ACCOUNT_DEPARTMENT_ACCOUNT", joinColumns = { @JoinColumn(name = "department_id", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "account_id", nullable = false, updatable = false) })
@Cascade( { CascadeType.SAVE_UPDATE })
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}
------解决方案--------------------为什么这类问题没有人来答呢。。
------解决方案--------------------你是用注解,我是使用配置文件,但我想问题都一样,你配一个inverse="true",就是设置主控方是谁,我是这样理解的,=ture就是为对方,那么在保存对方对象的时候,中间表会自动新增记录的,哦,好像还要配一个级联的保存与修改的属性吧,cascade="save-update",在配置文件中是这样配的,你根据这样配好试试看,能否保存了,我有一段时间没弄了,在搞C#,
------解决方案--------------------操作中都是类
------解决方案--------------------顶一下!!