在使用jsf+Spring+Hibernate做项目时,发现配置Hibernate的实体映射文件相当繁琐.前段时间做EJB时,一直采用的是JPA的注解方式.相比较之下,少写不少代码.于是花了些时间.将项目中原来使用xml配置的方式转成使用Annotation方式.记录如下:
注:为了使用Annotation,需将原HibernateSessionFactory.xml中sessionFactory的实现类改成:org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
com.singtel.system.model.Customer
注:原来使用mappingResources来配对hbm.xml文件,现用annotatedClasses来直接映射到指定Class.
Or:也可通过通配符来自动扫描类包
com.singtel.system.model.*
注: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