用hibernate 不能用Struts,spring,数据库用mysql,求助啊,各位大神,上课老师留的项目,结果木有做完,
2个回答
展开全部
自己新建一个操作数据库的类.类里面自己定义一个hibernate的SessionFatory属性.然后通过hibernate的Configuration对象去创建SessionFatory对象.将实体对象添加到SessionFactory管理.然后就可以通过SessionFatory创建hibernate的session对象了,有了session对象就可以对数据库进行操作了.里面的事务自己控制.hibernate配置文件自己写吧.就是一些类似jdbc的数据库连接信息.
简单代码如下:
static{
try{
// Create a configuration based on the properties file we've put
Configuration config = new Configuration();
config.setNamingStrategy( new MyNamingStrategy() )
.addClass(Customer.class)
.addClass(Order.class)
.addClass(Dictionary.class);
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
}catch(Exception e){e.printStackTrace();}
}
public Customer loadCustomer(long customer_id) throws Exception{
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(customer_id));
tx.commit();
return customer;
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
参考一下吧.
简单代码如下:
static{
try{
// Create a configuration based on the properties file we've put
Configuration config = new Configuration();
config.setNamingStrategy( new MyNamingStrategy() )
.addClass(Customer.class)
.addClass(Order.class)
.addClass(Dictionary.class);
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
}catch(Exception e){e.printStackTrace();}
}
public Customer loadCustomer(long customer_id) throws Exception{
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer customer=(Customer)session.load(Customer.class,new Long(customer_id));
tx.commit();
return customer;
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
参考一下吧.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询