在原项目中引入hibernate-annotations.jar和ejb3-persistence.jar
hibernate.cfg.xml配置改动不大,青年人网提示只是改一下mapping的方式,直接写类名。
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">1</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="org.leo.Order"/>
</session-factory>
</hibernate-configuration>
要注意的是SessionFactory实例化的方式。
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
一定要用AnnotationConfiguration
实体Bean的原hbm文件不用了。改为加Annotation
package org.leo;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="t_order")
public class Order implements Serializable {
private static final long serialVersionUID = 8896146925710456113L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int objID;
private String name;
public int getObjID() {
return objID;
}
public void setObjID(int objID) {
this.objID = objID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
责任编辑:小草