程序代码:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate. <session-factory>
<property name="myeclipse.connection.profile">JDBC for MySQL</property>
<property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/demo/hibernate/beans/po/User.hbm.xml" /></session-factory></Hibernate-configuration>
这是hibernate.cfg.xml
//HibernateSessionfactory代码
程序代码:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION="/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
private static final Configuration cfg=new Configuration();
private static SessionFactory sessionFactory;
public static Session currentSession()throws HibernateException{
Session session=(Session)threadLocal.get();
if(session==null){
if(sessionFactory==null){
try{
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory=cfg.configure().buildSessionFactory();
}catch(Exception e){
System.err.println("%%%% Error Creating SessionFatory %%%%");
}
}
session=sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession(){
Session session=(Session)threadLocal.get();
threadLocal.set(null);
if(session!=null){
session.close();
}
}
}
//User.hbm.xml
程序代码:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE Hibernate-maping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate. package="com.demo.hibernate.beans.po">
<class name="User" table="user">
<id name="id" column="id" type="integer">
<generator class="native"></generator>
</id>
<property name="username" column="username" type="string"></property>
<property name="password" column="password" type="string"></property>
<property name="email" column="email" type="string"></property></class></Hibernate-maping>
图片附件: 游客没有浏览图片的权限,请
登录 或
注册
图片附件: 游客没有浏览图片的权限,请
登录 或
注册