我从来没有通过加入3个表来编写Hibernate代码,而且我遇到了困难。
我有以下3个数据库表。
CREATE TABLE EMPLOYEE (
EMP_ID int(6) NOT NULL AUTO_INCREMENT,
EMP_NAME varchar(20) NOT NULL,
PRIMARY KEY (EMP_ID));
CREATE TABLE SKILLS (
SKILL_NAME varchar(20) NOT NULL,
PRIMARY KEY (SKILL_NAME)
);
CREATE TABLE EMPLOYEE_SKILLS(
EMPLOYEE_ID int(6) NOT NULL,
SKILL varchar(20) NOT NULL,
KEY EMPLOYEE_fk (EMPLOYEE_ID),
KEY SKILLS_fk (SKILL),
CONSTRAINT EMPLOYEE_fk FOREIGN KEY (`EMPLOYEE_ID`) REFERENCES `EMPLOYEE` (`EMP_ID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT SKILLS_fk FOREIGN KEY (`SKILL`) REFERENCES `SKILLS` (`SKILL_NAME`) ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE(EMPLOYEE_ID,SKILL)
);
请查找以下bean类:
@Entity
@Table(name = "EMPLOYEE")
public class EmployeeBean implements Serializable {
@Id
@Column(name="EMP_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int employeeid;
@Column(name="EMP_NAME")
private String employeeName;
//Add Mappings here
}
@Entity
@Table(name="SKILLS")
public class SkillsBean implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="SKILL_NAME", unique = true)
private String skillName;
//Add your mappings here
}
@Entity
@Table(name = "EMPLOYEE_SKILLS")
public class EmployeeSkillsBean implements Serializable {
@Embeddable
public static class Id implements Serializable {
@Column(name="EMPLOYEE_ID")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int employeeId;
@Column(name="SKILL")
private String skillName;
public Id() {
}
public Id(int employeeId, String skillName) {
this.employeeId = employeeId;
this.skillName = skillName;
}
public boolean equals(Object obj) {
if(obj != null && obj instanceof Id) {
Id idObj = (Id)obj;
return this.employeeId == idObj.employeeId && this.skillName.equals(idObj.skillName) ;
} else {
return false;
}
}
public int hashcode() {
return employeeId+"".hashCode() + skillName.hashCode();
}
}
@EmbeddedId
private Id id = new Id();
//Add your mappings here
}
我的要求是,从UI(JSP),用户输入员工姓名和技能名称,它应插入到EMPLOYEE_SKILLS表中。这个表格包含多名员工及其多种技能。
您可以通过向上述Bean添加所需的Hibernate映射来帮助您吗?您也可以帮助了解DAO insert()方法如何将员工姓名和技能保存到EMPLOYEE_SKILLS表中?
答案 0 :(得分:-1)
@Entity
@Table(name = "EMPLOYEE")
public class EmployeeBean implements Serializable {
@Id
@Column(name="EMP_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int employeeid;
@Column(name="EMP_NAME")
private String employeeName;
@OneToMany(mappedBy="employee")
private List<SkillsBean> skills;
//Add Mappings here
}
@Entity
@Table(name="SKILLS")
public class SkillsBean implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="SKILL_NAME", unique = true)
private String skillName;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="EMP_ID")
private EmployeeBean employee;
//Add your mappings here
}
我假设一名员工可以拥有很多技能