在使用jsf+Spring+Hibernate做項目時,發現配置Hibernate的實體映射文件相當繁瑣.前段時間做EJB時,一直采用的是JPA的注解方式.相比較之下,少寫不少代碼.于是花了些時間.將項目中原來使用xml配置的方式轉成使用Annotation方式.記錄如下:
<!--
Hibernate session factory
-->
<!--
For using no-Annotation
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
-->
<!--
using for Annotation
-->
<
bean
id
="sessionFactory"
class
="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
>
注:為了使用Annotation,需將原HibernateSessionFactory.xml中sessionFactory的實現類改成:org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
<!--
<property name="mappingResources">
<list>
<value>com/singtel/config/hibernate/Customer.hbm.xml </value>
</list>
</property>
-->
<!--
Using for Annotation
-->
<
property
name
="annotatedClasses"
>
<
list
>
<
value
>
com.singtel.system.model.Customer
</
value
>
</
list
>
</
property
>
注:原來使用mappingResources來配對hbm.xml文件,現用annotatedClasses來直接映射到指定Class.
Or:也可通過通配符來自動掃描類包
<
property
name
="packagesToScan"
>
<
list
>
<
value
>
com.singtel.system.model.*
</
value
>
</
list
>
</
property
>
注:packagesToScan是Spring 2.5.6新特性(推薦)
接下來要做的就是在java實體中增加注解.
package
com.singtel.system.model;
import
java.io.Serializable;
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.Table;
import
javax.persistence.Temporal;
import
javax.persistence.TemporalType;
@Entity(name
="Customer"
)
@Table(name
="CUSTOMER_LWC"
)
public
class
Customer
implements
Serializable{
@Id
@Column(name
="CUSTOMER_ID",columnDefinition = "Integer"
)
@GeneratedValue(strategy
=
GenerationType.AUTO)
public
long
customerId;
@Column(name
="CUSTOMER_ADDRESS",columnDefinition = "varchar2(255)", nullable =
false
)
public
String address;
@Column(name
="CUSTOMER_PASSWORD",columnDefinition = "varchar2(45)", nullable =
false
)
public
String password;
@Column(name
= "CREATED_DATE", nullable =
false
)
@Temporal(TemporalType.TIMESTAMP)
public
Date createdDate;
public
long
getCustomerId() {
return
customerId;
}
public
void
setCustomerId(
long
customerId) {
this
.customerId =
customerId;
}
public
String getPassword() {
return
password;
}
public
void
setPassword(String password) {
this
.password =
password;
}
public
String getAddress() {
return
address;
}
public
void
setAddress(String address) {
this
.address =
address;
}
public
Date getCreatedDate() {
return
createdDate;
}
public
void
setCreatedDate(Date createdDate) {
this
.createdDate =
createdDate;
}
}
刪除原有hbm.xml.Ok
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

