本教程将重用和修改以前的Hibernate3.6 XML映射教程 ,但将Hibernate映射文件(hbm)替换为Hibernate / JPA注释代码。
本文中的技术:
- Maven的3.0.3
- JDK 1.6.0_13
- 休眠3.6.3。最终
- 甲骨文11g
1. pom.xml
pom.xml
文件中没有任何更改,所有以前的Hibernate3.6 XML映射教程依赖项都可以重用。
注意
从Hibernate 3.6开始,注释已集成到hibernate-core.jar
模块中。 在以前的版本(例如,Hibernate 3.2)中,您需要包括额外的hibernate-annotations.jar
以使其起作用。
2.删除休眠映射文件(hbm)
删除不再需要的“ DBUser.hbm.xml
”文件。
3.更新模型
更新“ DBUser.java
”,将JPA注释代码放入其中。
文件:DBUser.java
package com.mkyong.user;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "DBUSER")
public class DBUser implements java.io.Serializable {
private int userId;
private String username;
private String createdBy;
private Date createdDate;
public DBUser() {
}
public DBUser(int userId, String username, String createdBy,
Date createdDate) {
this.userId = userId;
this.username = username;
this.createdBy = createdBy;
this.createdDate = createdDate;
}
@Id
@Column(name = "USER_ID", unique = true, nullable = false, precision = 5, scale = 0)
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Column(name = "USERNAME", nullable = false, length = 20)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "CREATED_BY", nullable = false, length = 20)
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
@Temporal(TemporalType.DATE)
@Column(name = "CREATED_DATE", nullable = false, length = 7)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
4.更新休眠配置文件
更新“ hibernate.cfg.xml
”,将“ 映射资源 ”替换为“ 映射类 ”
从此更新hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<!-- ..... -->
<mapping resource="com/mkyong/user/DBUser.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
对此:
<hibernate-configuration>
<session-factory>
<!-- ..... -->
<mapping class="com.mkyong.user.DBUser"></mapping>
</session-factory>
</hibernate-configuration>
5.休眠实用程序
自Hibernate 3.6起,“ HibernateUtil.java
”没有更新,因此XML映射和注释都共享相同的“ org.hibernate.cfg.Configuration ”类。
再见AnnotationConfiguration
阅读本文– Hibernate 3.6中不推荐使用AnnotationConfiguration
6.审查最终项目结构
查看您的项目结构:
7.运行
同样,“ App.java
”也没有更新,只需运行它,您应该会看到与以前的Hibernate3.6 XML映射教程相同的结果。
下载它– Maven3-Hibernate3.6-Oracle11-Annotation-Example.zip (7KB)
参考
翻译自: https://mkyong.com/hibernate/maven-3-hibernate-3-6-oracle-11g-example-annotation/