我正在使用Spring + JPA + Hibernate开发一个网站。在持久性配置(JPA + Hibernate)中,我将HibernateJpaVendorAdapter的generateDdl属性设置为true,实际上新实体在数据库中正确创建了新表。
但是,一旦创建了表,如果我向实体添加属性,我希望HibernateJpaVendorAdapter能够更改表并添加列。这没有发生,这很奇怪,因为在Java AbstractJpaVendorAdapter的setGenerateDdl方法文档中有:“设置是否在EntityManagerFactory初始化后创建, 更新 / 更新 所有相关表后生成DDL 。”
JPA + Hibernate配置:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${db.driverClassName}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> </bean> <bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" /> <property name="showSql" value="${db.showSql}" /> <property name="generateDdl" value="${db.generateDdl}" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter" ref="jpaAdapter" /> <property name="jpaProperties"> <props> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="dataSource" ref="dataSource" /> </bean>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="m8tsPU" /> </persistence>
难道我做错了什么?
通过直接设置适当的特定于Hibernate的属性,您可以对DDL生成进行更细粒度的控制:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> ... <property name="jpaProperties"> <props> <prop key="hibernate.hbm2ddl.auto">update</prop> ... </props> </property> </bean>
或者,可以使用create-drop代替update,因为update在某些情况下可能会引起问题。但是请注意,自动DDL更新不适合生产使用。
create-drop
update