使用Annotation开发Hibernate
Hibernate提供有以下注解:
注解 | 说明 |
---|---|
@Entity | 标识当前类为实体类,使用默认 ORM 规则,即类名映射数据库中对应的表名,属性名映射数据表中列名。 |
@Table | 如果类名和数据表名不一致,使用 @Table(name = "数据表名") 标识当前类对应的数据表名。 |
@Id | 当前实体类的唯一性标识,通常映射到数据表主键。 |
@GeneratedValue | 实体类唯一标识生成规则 |
@GenericGenerator | 唯一标识生成器 |
@Temporal | 限制时间格式,具体如下。 |
TemporalType.DATE – 只记录日期,不记录时间
TemporalType.TIME – 只记录时间,不记录日期
TemporalType.TIMESTAMP – 日期时间都记录(默认)
注解 | 说明 |
---|---|
@Column | 如果当前类中属性名与对应数据表中的列名不一致,使用 @Column(name = "数据表列名") 标识此属性对应的数据表列名,此外可以使用@Column(length = 30) 限制字符串长度。 |
@Transient | 标识当前属性不映射任何数据表列。 |
在IDEA中使用Annotation配置Hibernate只需要在POJO类创建的时候选择即可。
此时的hibernate.cfg.xml文件会出现:
<mapping class="com.gub.vo.Dept"/>
其中class属性表示POJO类,所有的Annotation都写在此类中
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
@Entity//表示这是一个数据实体类型
public class Dept {
private int deptno;
private String dname;
private String address;
private String tel;
private Date credate;
@Id//设置主键属性
@Column(
name = "deptno", //主键列名称
unique = true, //是否唯一
nullable = false, //是否允许为空
length=30 //字段长度
)
public int getDeptno() {//此方法返回的内容为主键列
return deptno;
}
public void setDeptno(int deptno) {//Setter无变化
this.deptno = deptno;
}
@Basic
@Column(name = "dname")//定义dname列映射
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
@Basic
@Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Basic
@Column(name = "tel")
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Basic
@Column(name = "credate")
@Temporal(TemporalType.DATE)//定义的是日期型字段
public Date getCredate() {
return credate;
}
public void setCredate(Date credate) {
this.credate = credate;
}
}
此时编写测试类,与使用*.hbm.xml相同
import com.gub.dbc.HibernateSessionFactory;
import com.gub.vo.Dept;
import java.util.Date;
public class AnnotationTest {
public static void main(String[] args) {
HibernateSessionFactory.getSession().save(getDept());
HibernateSessionFactory.getSession().beginTransaction().commit();
HibernateSessionFactory.closeSession();
}
public static Dept getDept(){
Dept dept = new Dept();
dept.setDeptno(5);
dept.setDname("宣传部");
dept.setAddress("SH");
dept.setTel("0471-49815256");
dept.setCredate(new Date());
return dept;
}
}
运行程序得到以下结果:
打开数据库,发现数据存入正常,Annotation配置完成
【利用SchemaExport工具实现数据表的生成】
利用 org.hibernate.tool.hbm2ddl.SchemaExport
可以实现数据库脚本的生成。
生成脚本:
public void create(boolean script,boolean export);
使用SchemaExport根据配置文件生成脚本
import com.gub.dbc.HibernateSessionFactory;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class SchemaTest {
public static void main(String[] args) {
/*
Configuration类的主要作用是读取配置文件,也就是hibernate.cfg.xml文件,而所有的
*.hbm.xml文件或者是所有的Annotation支持,都要在公共配置文件中进行配置
*/
SchemaExport schemaExport = new SchemaExport(HibernateSessionFactory.getConfiguration());
schemaExport.create(true,true);
}
}
执行结果: