日期:2014-05-20  浏览次数:20760 次

hibernate新手问题哪个格我解决下啊
Hibernate.cfg.xml
 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD3.0//EN" "hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
<property name="connection.url">jdbc:firebirdsql:[//host[:port]/]&lt;database&gt;</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- 将Hibernate发送给数据库的sql显示出来 -->
<property name="show_sql">true</property>
<!-- Mapping files -->
<property name="myeclipse.connection.profile">SQL</property>
<mapping resource="model/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
----------------------------------------------------------------------
 HibernateSessionFactory.java


package util;
import model.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateSessionFactory {
private static SessionFactory factory;
static 
{
Configuration cfg=new Configuration();
cfg.addClass(User.class);
factory=cfg.buildSessionFactory();
}
public static Session getSession()
{
return factory.openSession();
}

}
-------------------------------------------------

Dao.java


package util;
import model.*;
import org.hibernate.*;
import org.hibernate.cfg.*;



public class Dao {

public void insertUser(User user)throws Exception
{
Session session=null;
Transaction tran=null;
try
{
session=HibernateSessionFactory.getSession();
tran=session.beginTransaction();
session.save(user);
tran.commit();
}
catch(Exception e)
{
tran.rollback();
throw e;
}finally
{
if(session!=null)
{
session.close();
}
}


}
public void updateUser(User user)throws Exception
{
Session session=null;
Transaction tran=null;
try
{
session=HibernateSessionFactory.getSession();
tran=session.beginTransaction();
session.saveOrUpdate(user);
tran.commit();
}
catch(Exception e)
{
tran.rollback();
throw e;
}finally
{
if(session!=null)
{
session.close();
}
}
}
public User queryUserById(String userID)throws Exception
{
Session session=null;

try
{
session=HibernateSessionFactory.getSession();

User user=(User)session.load(User.class,userID);
return user;

}
finally
{
if(session!=null)
{
session.close();
}
}
}
public void deleteUser(String userID)throws Exception
{
Session session=null;
Transaction tran=null;
try
{
session=HibernateSessionFactory.getSession();
tran=session.beginTransaction();
session.delete(userID, User.class);
tran.commit();
}
catch(Exception e)
{
tran.rollback();
throw e;
}finally
{
if(session!=null)
{
session.close();
}
}

}

}
------------------------------------------------------