hibernate12--注解
在之前的基础上删除hbm.xml映射文件
之后修改实体类内容
/** * 部门的实体类 * strategy对应的就是主键生成策略 * GenerationType: * 01.auto:自动选择合适的策略,而且是默认值 * 02.identity:主键自增 * 03.sequence:通过序列产生主键 * 04.table:通过表来生成主键!框架依赖数据库中的表!模拟序列产生主键! */ @Entity public class Dept { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer deptNo; private String deptName; @Transient //忽略映射属性 输出值 null private String location; //一个部门对应多个员工 @OneToMany(mappedBy="dept",cascade={CascadeType.ALL}) private Set<Emp> emps=new HashSet<>(); public Integer getDeptNo() { return deptNo; } public void setDeptNo(Integer deptNo) { this.deptNo = deptNo; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Set<Emp> getEmps() { return emps; } public void setEmps(Set<Emp> emps) { this.emps = emps; } public Dept(Integer deptNo, String deptName, String location, Set<Emp> emps) { super(); this.deptNo = deptNo; this.deptName = deptName; this.location = location; this.emps = emps; } public Dept() { super(); } @Override public String toString() { return "Dept [deptNo=" + deptNo + ", deptName=" + deptName + ", location=" + location + ", emps=" + emps.size() + "]"; } }
/** * @author 小豆腐 *员工的实体类 */ @Entity public class Emp { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_emp") @SequenceGenerator(name="seq_emp",sequenceName="sq_student_id") private Integer empNo; private String empName; private String job; @Column(name="salary") private Double sal; private Date hireDate; //多个员工属于一个部门 @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="deptNo") private Dept dept; public Integer getEmpNo() { return empNo; } public void setEmpNo(Integer empNo) { this.empNo = empNo; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Double getSal() { return sal; } public void setSal(Double salary) { this.sal = salary; } public Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } public Emp(Integer empNo, String empName, String job, Double salary, Date hireDate, Dept dept) { super(); this.empNo = empNo; this.empName = empName; this.job = job; this.sal = salary; this.hireDate = hireDate; this.dept = dept; } public Emp() { super(); } @Override public String toString() { return "Emp [empNo=" + empNo + ", empName=" + empName + ", job=" + job + ", salary=" + sal + ", hireDate=" + hireDate + ", dept=" + dept + "]"; } }
在hibernate.cfg.xml中管理 实体类
<!--加载我们配置 注解类 --> <mapping class="cn.bdqn.bean.Dept" /> <mapping class="cn.bdqn.bean.Emp" />