【发布时间】:2017-02-16 11:56:58
【问题描述】:
Hibernate 不创建任何表:
我有一个 Tomcat 服务器,我的 jsf/hibernate 项目在该服务器上运行。数据库服务器是MySQL 服务器。启动没有问题,但不创建任何表。
我创建了一个没有 Tomcat 服务器和任何其他东西的新项目。只有 Hibernate 相关的代码。仍然没有错误和警告,但也没有创建表。
休眠配置 (hibernate.cfg.xml):
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/3bt_database</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="hbm2ddl.auto">create</property>
<mapping class="model.Testtable"/>
</session-factory>
</hibernate-configuration>
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionfactory = buildSessionFactory();
public static SessionFactory buildSessionFactory() throws HibernateException {
try {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionfactory(){
return sessionfactory;
}
}
StartStopListener:
@WebListener
public class StartStopListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
HibernateUtil.getSessionfactory().openSession();
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
HibernateUtil.getSessionfactory().close();
}
}
测试表:
@Entity
@Table(name="tblTest")
public class Testtable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int testID;
private String testname;
}
请不要告诉我手动创建它们。这不是我正在寻找的答案。
【问题讨论】:
-
您使用的是哪个休眠版本?您的数据库有密码吗?任何控制台错误或警告?
-
休眠 5.2.2。不,为了测试,我故意使用 root 和空白。
-
是
Testtable类的包名是model? -
创建 SessionFactory,版本变化,试试这个 -> docs.jboss.org/hibernate/orm/5.2/userguide/html_single/…
-
尝试在每个属性名称中添加
hibernate.
标签: java mysql hibernate tomcat