hibernate——多表关系映射之多对多第一篇(常规)

本篇文章以Employee(员工)和Role(角色)为例讲述多对多映射关系的配置。

第一步:建表(MySQL)

#员工表
CREATE TABLE employee (
ID INT(2) PRIMARY KEY AUTO_INCREMENT,
NAME CHAR(10) NOT NULL,
AGE INT(2) NOT NULL);

#角色表
CREATE TABLE role (
ID INT(2) PRIMARY KEY AUTO_INCREMENT,
NAME CHAR(10) NOT NULL);

#关系表
CREATE TABLE employee_role_table (
EMPLOYEE_ID INT(2),
ROLE_ID INT(2),
FOREIGN KEY(EMPLOYEE_ID) REFERENCES employee(ID),
FOREIGN KEY(ROLE_ID) REFERENCES role(ID));

第二步:编写实体类

//Employee.java
public class Employee implements Serializable {

	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private Integer age;
	private Set roles = 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 getRoles() {
		return roles;
	}
	public void setRoles(Set roles) {
		this.roles = roles;
	}
	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;
	private Set employees = new HashSet<>();
	
	public Role(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public Role() {
		super();
	}
	public Set getEmployees() {
		return employees;
	}
	public void setEmployees(Set employees) {
		this.employees = employees;
	}
	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)