02_hibernate5快速入门_注解的方式

来源:互联网 发布:爱情观知乎 编辑:程序博客网 时间:2024/06/05 11:19

接上一章文章http://blog.csdn.net/hnzmdpan/article/details/72790929,本文以注解的形式,实现了和上文一样的功能。


hibernate.cfg.xml文件里,把mapping标签的地方改一下,由原来的resource=xxx,换成class=xxx

<mapping class="org.hibernate.tutorial.annotations.Event"/>

Event的代码如下所示
package org.hibernate.tutorial.annotations;import java.util.Date;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;import org.hibernate.annotations.GenericGenerator;@Entity@Table( name = "EVENTS" )public class Event {    private Long id;    private String title;    private Date date;public Event() {// this form used by Hibernate}public Event(String title, Date date) {// for application use, to create new eventsthis.title = title;this.date = date;}@Id@GeneratedValue(generator="increment")@GenericGenerator(name="increment", strategy = "increment")    public Long getId() {return id;    }    private void setId(Long id) {this.id = id;    }@Temporal(TemporalType.TIMESTAMP)@Column(name = "EVENT_DATE")    public Date getDate() {return date;    }    public void setDate(Date date) {this.date = date;    }    public String getTitle() {return title;    }    public void setTitle(String title) {this.title = title;    }}
解释一下上面的代码,可以看到导入的类中,好多都是JPA,那么什么是JPA呢?Java Persistence API,更详细的可以百度下。Hibernate5.0.12,用到的JPA版本是2.1,所以里面出现了好多的JPA的注解。

@Entity,可以理解为,该类在数据库有一张表与其对应。
@Table,该类在数据库中的名字。可以不写,不写的话,表名就和该类名一样。
@Id,表中的标识
@GeneratedValue和@GenericGenerator通常一起使用,表示主键的值的生成方式,专业述语为ID的生成策略
@Column,定义列名。
@Temporal,定义日期日间的格式。DATE(java.sql.Date), TIME(java.sql.Time), TIMESTAMP(java.sql.Timestamp)
值得说的明的,类中的属性,默认情况下都会被Hibernate持久化。简单而言,都是会被Hibernate管理。


源代码 https://git.oschina.net/hnzmdpan/hibernate.git 分支为quickstart_annotations。


最后,我建了个 QQ群622539266,Java知识交流,期待你的加入。

原创粉丝点击