我有一个非常简单的maven + hibernate项目。
我想检索数据并使用命令"从产品"中选择*在控制台中打印数据。但每次启动我的应用程序时,它都会重建db中的所有表,因此会删除所有数据。
我应该怎么做才能在每次启动应用程序时重新构建表格?
Main.java
public class Main {
static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
List<Object> products = null;
try {
session.beginTransaction();
SQLQuery query = session.createSQLQuery("select * from product");
query.addEntity(Product.class);
products = query.list();
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
sessionFactory.close();
}
System.out.println("Hello");
for (Iterator iterator = products.iterator(); iterator.hasNext(); ) {
Product product = (Product) iterator.next();
logger.info("Hello");
}
}
的hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">****</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.jdbc.lob.non_contextual_creation">true</property>
<mapping class="models.User"/>
<mapping class="models.Role"/>
<mapping class="models.Product"/>
<mapping class="models.ProductCategory"/>
<mapping class="models.Order" />
</session-factory>
</hibernate-configuration>
答案 0 :(得分:1)
更改行
<property name="hbm2ddl.auto">create</property>
通过
<property name="hbm2ddl.auto">validate</property>
答案 1 :(得分:1)
在hibernate.cfg.xml文件中使用以下代码
<property name="hbm2ddl.auto">Update</property>
而不是
<property name="hbm2ddl.auto">create</property>