- Hibernate的双向关联。 对象之间可以相互读取。 双向只针对读取的操作。对于增、删除、改的操作没有任何影响。
案例 : 实现双向多对多
- MenuBean.java
package bean;import java.io.Serializable;import java.util.HashSet;import java.util.Set;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;import javax.persistence.Table;@Entity@Table(name = "menu")public class MenuBean implements Serializable { @Id private Integer menuid; private String menuname; @ManyToMany @JoinTable(name = "role_menu", //指定数据库中的中间表 joinColumns = @JoinColumn(name = "menu_id"), //设置当前实体在中间表中的映射,也就是说在中间表中有一个字段叫menu_id,使它指向当前表的主键这里是menuid inverseJoinColumns = @JoinColumn(name = "roleid") //设置对方实体在中间中的映射,也就是说在中间表中有一个字段roleid,使它指向对方表的主键。 ) private SetroleSet = new HashSet (); public MenuBean(Integer menuid, String menuname) { super(); this.menuid = menuid; this.menuname = menuname; } public MenuBean() { super(); // TODO Auto-generated constructor stub } public Integer getMenuid() { return menuid; } public void setMenuid(Integer menuid) { this.menuid = menuid; } public String getMenuname() { return menuname; } public void setMenuname(String menuname) { this.menuname = menuname; } public Set getRoleSet() { return roleSet; } public void setRoleSet(Set roleSet) { this.roleSet = roleSet; }}
- RoleBean.java
package bean;import java.io.Serializable;import java.util.HashSet;import java.util.Set;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;import javax.persistence.Table;@Entity@Table(name = "role")public class RoleBean implements Serializable { @Id private Integer role_id; private String role_name; private String role_remark; @ManyToMany @JoinTable(name = "role_menu", joinColumns = @JoinColumn(name = "roleid"), inverseJoinColumns = @JoinColumn(name = "menu_id")) private SetmenuSet = new HashSet (); public RoleBean(Integer role_id, String role_name, String role_remark) { super(); this.role_id = role_id; this.role_name = role_name; this.role_remark = role_remark; } public RoleBean() { super(); // TODO Auto-generated constructor stub } public Integer getRole_id() { return role_id; } public void setRole_id(Integer role_id) { this.role_id = role_id; } public String getRole_name() { return role_name; } public void setRole_name(String role_name) { this.role_name = role_name; } public String getRole_remark() { return role_remark; } public void setRole_remark(String role_remark) { this.role_remark = role_remark; } public Set getMenuSet() { return menuSet; } public void setMenuSet(Set menuSet) { this.menuSet = menuSet; }}
- 添加到总配置文件即可实现。