我正在使用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更新不适合生产使用。

关于HibernateJpaVendorAdapter的generateDdl不会更改表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8975577/

10-10 16:02