使用annotation的Entity Java Class代替XXXX.hbm.xml
前一篇文章里的例子中的Event.hbm.xml就变成了:
@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 events
this.title = title;
this.date = date;
}
@Id
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment")
public Long getId() {
return id;
}
public 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;
}
}
其中:
@javax.persistence.Entity : 标识一个Class是一个Entity class。与.hbm.xml中的class对应。
@javax.persistence.Table : 数据库表的名字。
@javax.persistence.Id : 主键。
@GeneratedValue(generator="increment")
@GenericGenerator(name="increment", strategy = "increment") : 标识id的生成策略。
与此对应,hibernate.cfg.xml中的mapping变为了:
<!-- mapping resource="org/hibernate/tutorial/hbm/Event.hbm.xml"/ -->
<mapping class="org.hibernate.tutorial.annotation.Event"/>
.
其他,与前一篇文章相同,不变。