hibernate——多表关系映射之多对多第二篇(主键外的其它字段映射)

在第一篇中写了多表映射之多对多的常规配置,即关联表中只有以其它表主键做外键的字段。第一篇链接

这一篇是讲述多对多映射时,关联表如何配置非主键字段。依然以Employee与Role为例

与常规配置相比需要多编写一个实体类,例EmployeeAndRole.java,该实体类应包含Employee类和Role类对象,并提供getter、setter方法。如下:

public class EmployeeAndRole implements Serializable {

	private static final long serialVersionUID = 1L;
	private Employee employee;
	private Role role;
	
	public Employee getEmployee() {
		return employee;
	}
	public void setEmployee(Employee employee) {
		this.employee = employee;
	}
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
}

编写此实体类之后,原来的Employee.java、Role.java也需要做相应修改,如下:

//Employee.java
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private Integer age;
        // 注意!!!
        // 集合应该为EmployeeAndRole实体类的集合
	private Set employeeAndRoles = new HashSet<>();
	
	public Employee(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age= age;
	}
	public Employee() {
		super();
	}
	
	public Set getEmployeeAndRoles() {
		return employeeAndRoles;
	}
	public void setEmployeeAndRoles(Set employeeAndRoles) {
		this.employeeAndRoles = employeeAndRoles;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}

//Role.java
public class Role implements Serializable {

	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
        // 注意!!!
        // 集合应该为EmployeeAndRole实体类的集合
	private Set employeeAndRoles = new HashSet<>();
	
	public Role(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public Role() {
		super();
	}
	public Set getEmployeeAndRoles() {
		return employeeAndRoles;
	}
	public void setEmployeeAndRoles(Set employeeAndRoles) {
		this.employeeAndRoles = employeeAndRoles;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

映射配置文件同时也需要进行修改,这里会用到等标签,拭目以待。



    
        
            
        
        
        
        
        
            
            
            
            
                
                
                
                
                                         
                
                    
                    
                
                
            
        
     




    
        
            
        
        
        
            
            
                
                
            
        
    

解释已在代码注释中标注,另外补充:添加字段时只在维护映射关系的一端添加配置即可,放弃维护的一端不需要配置。

你可能感兴趣的:(Hibernate)