项目加了个struts2和一个hibernate,并且配置了update 为什么无效呢?
没有自动创建表。
不能自动创建表格;看看你的主键生成机制;对应的javaBean类型是或一致;如:选主键机制是uuid.hex 而javaBean中id是int类型;就不会报错;但就是不会自动创建表。
看看后台报什么错了,
把配置文件贴出来看一下
检查一下:
或者
或者
写了没有?有错没有?
hibernate配置跟web无关的,不需要配置任何监听同样可以完成hibernate配置工作,配置了hibernate.cfg.xml文件后,由Configuration来加载hibernate.cfg.xml文件,然后通过sessionFactory来openSession,这样就可以对数据库进行操作了.
http://z276356445t.iteye.com/blog/975460
是关于SSH+Freemarker整合的.
没有spring,就用全局变量(单例模式)。不用配置web.xml。
[code="java"]public class MyAppCtx {
private static Configuration cfg = new Configuration();
static {
cfg.addResource(....);
}
private static SessionFactory sessionFactory = cfg.buildSessionFactory();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}[/code]
缺点很显然,所有要使用sessionFactory的类,都依赖这个类。所以,用spring还是好。
当然,如果真的讨厌全局变量,可以设置一个监听器,在这个web应用初始化的时候创建这个SessionFactory。
虽然hibernate和web无关,正因为这样你需要自己初始化hibernate的sessionFactory,比如在某个listener或servlet,或者在每次action调用,总之要有这样的初始化,类似的代码如下:
[code="java"]
SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();
[/code]
请问作者的hibernate初始在哪里完成的?
你没有手动的装载hibernate.cfg.xml文件,给你一个官方自带的创建sessionFactory的例子.
[code="java"]
package com.sessionFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
/**
{@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
SessionFactory
if needed.@throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
/**
/**
@throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
/**
/**
}
[/code]
session通过这个里面去取.
实现javax.servlet.ServletContextListener。
然后加到web.xml里:(假设your.package.YourListener实现上述接口)
[code="xml"]
your.package.YourListener
[/code]
[code="java"]
public class HibernateInitListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent arg0) {
SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory();
//把sf放到一个全局对象里面,在action需要访问sessionFactory可以获取
}
public void contextDestroyed(ServletContextEvent arg0) {
//销毁应用的sessionFactory
}
}
[/code]
参考一下,作者可以自己写类似这样的代码。
童鞋,你撞枪口上了,适合这个正式2.1.2的一个BUG,看看:[url]https://issues.apache.org/jira/browse/WW-2633[/url]