Hibernate配置(通过注解配置)
本文主要讲通过注解配置来替换Hibernate的映射文件
1.多对一配置
package com.jazz7.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; // 1.注册bean @Entity // 2.和数据库表进行关联,如果名字不同的话,需要在这里指定name @Table public class Emp { // 3.配置id @Id //4.配置主键生成策略 @GeneratedValue(generator="empgener",strategy=GenerationType.SEQUENCE) //配置序列 @SequenceGenerator(name="empgener",sequenceName="seq_emp_id",allocationSize=1,initialValue=1) private int empno; private String ename; private String job; private Integer mgr; private Date hiredate; private float sal; private Float comm; //多对一关联 @ManyToOne(targetEntity=Dept.class) //配置外键 @JoinColumn(name="deptno") private Dept dept; // ......省略get()set() }
2.一对多配置
@Entity @Table public class Dept { @Id @Column private int deptno; private String dname; private String loc; //一对多配置 @OneToMany(mappedBy="dept") private Set<Emp> emps; // ...省略get()set() }
3.多对多配置
@Entity @Table(name = "tbl_student") public class Student { @Id @Column @GeneratedValue(generator = "stname", strategy = GenerationType.SEQUENCE) @SequenceGenerator(name = "stname", sequenceName = "seq_student_id", allocationSize = 1, initialValue = 1) private int sid; private String sname; // 多对多配置 @ManyToMany(targetEntity=Teacher.class,mappedBy="students") //配置“关系表”,joinColumns是“本类”在关系表中的外键,inverseJoinColumns是相关联类在关系表中的外键 @JoinTable(name = "tbl_teacher_student", joinColumns ={@JoinColumn(columnDefinition="sid")}, inverseJoinColumns = {@JoinColumn(columnDefinition="tid")}) private Set<Teacher> teachers; // ...省略get()set() }
欢迎提出意见或建议!!!