Spring Hibernate без создания таблиц

1

Я создал базу данных и сгенерировал некоторые сущности из нее. Теперь я хочу подключиться к Spring framework. Проблема в том, что когда я развертываю Wildfly, он пытается создать таблицы в моей базе данных и терпит неудачу, потому что там есть таблицы.

Мой файл context.xml выглядит следующим образом

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="
                        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
                        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <context:annotation-config />

    <!--
           DATABASE SETUP 
    -->

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="username" value="****" />
        <property name="password" value="****" />
        <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@1.1.1.1:1521:XE" />
    </bean>

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="persistenceUnitName" value="examplePU" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="databasePlatform" value="org.hibernate.dialect.Oracle10gDialect" />
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="userDao" class="com.foobar.dao.user.JpaUserDao">
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />

    <!--
           INIT REST COMPONENTS 
    -->

    <context:component-scan base-package="com.foobar.rest.resources" />

    <bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper" />

    <!-- 
            SPRING SECURITY SETUP
    -->

    <bean id="passwordEncoder" class="com.foobar.security.SaltedSHA256PasswordEncoder">
        <constructor-arg value="secret" />
    </bean>

    <security:authentication-manager id="authenticationManager">
        <security:authentication-provider user-service-ref="userDao">
            <security:password-encoder ref="passwordEncoder"></security:password-encoder>
        </security:authentication-provider>
    </security:authentication-manager>

    <security:http
        realm="Protected API"
        use-expressions="true"
        auto-config="false"
        create-session="stateless"
        entry-point-ref="unauthorizedEntryPoint"
        authentication-manager-ref="authenticationManager">
        <security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
        <security:intercept-url pattern="/rest/user/authenticate" access="permitAll" />
        <security:intercept-url method="GET" pattern="/rest/news/**" access="hasRole('user')" />
        <security:intercept-url method="PUT" pattern="/rest/news/**" access="hasRole('admin')" />
        <security:intercept-url method="POST" pattern="/rest/news/**" access="hasRole('admin')" />
        <security:intercept-url method="DELETE" pattern="/rest/news/**" access="hasRole('admin')" />
    </security:http>

    <bean id="unauthorizedEntryPoint" class="com.foobar.rest.UnauthorizedEntryPoint" />

    <bean class="com.foobar.rest.AuthenticationTokenProcessingFilter" id="authenticationTokenProcessingFilter">
        <constructor-arg ref="userDao" />
    </bean>

</beans>

Это журнал от дикой

2014-04-02 22:31:54,170 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 41) JBAS014613: Operation ("deploy") failed - address: ([("deployment" => "portal-web-1.0-SNAPSHOT.war")]) - failure description: {"JBAS014671: Failed services" => {"jboss.persistenceunit.\"portal-web-1.0-SNAPSHOT.war#OneW2\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"portal-web-1.0-SNAPSHOT.war#OneW2\": javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [***]
    Caused by: javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [***]
    Caused by: org.h2.jdbc.JdbcSQLException: Table \"XXX\" already exists; SQL statement:
*** [42101-173]"}}
2014-04-02 22:31:54,172 ERROR [org.jboss.as.server] (management-handler-thread - 41) JBAS015870: Deploy of deployment "portal-web-1.0-SNAPSHOT.war" was rolled back with the following failure message: 
{"JBAS014671: Failed services" => {"jboss.persistenceunit.\"portal-web-1.0-SNAPSHOT.war#OneW2\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"portal-web-1.0-SNAPSHOT.war#OneW2\": javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [***]
    Caused by: javax.persistence.PersistenceException: Unable to execute JPA schema generation create command [***]
    Caused by: org.h2.jdbc.JdbcSQLException: Table \"XXX\" already exists; SQL statement:
*** [42101-173]"}}
2014-04-02 22:31:54,174 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-4) JBAS010418: Stopped Driver service with driver-name = portal-web-1.0-SNAPSHOT.war_org.hsqldb.jdbc.JDBCDriver_2_2
2014-04-02 22:31:54,173 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 77) JBAS011410: Stopping Persistence Unit (phase 2 of 2) Service 'portal-web-1.0-SNAPSHOT.war#examplePU'
2014-04-02 22:31:54,177 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 76) JBAS011410: Stopping Persistence Unit (phase 1 of 2) Service 'portal-web-1.0-SNAPSHOT.war#examplePU'
2014-04-02 22:31:54,177 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 77) JBAS011410: Stopping Persistence Unit (phase 1 of 2) Service 'portal-web-1.0-SNAPSHOT.war#OneW2'
2014-04-02 22:31:54,336 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-5) JBAS015877: Stopped deployment portal-web-1.0-SNAPSHOT.war (runtime-name: portal-web-1.0-SNAPSHOT.war) in 163ms
2014-04-02 22:31:54,337 INFO  [org.jboss.as.controller] (management-handler-thread - 41) JBAS014774: Service status report
JBAS014775:    New missing/unsatisfied dependencies:
      service jboss.deployment.unit."portal-web-1.0-SNAPSHOT.war".component."com.sun.jersey.spi.spring.container.servlet.SpringServlet".CREATE (missing) dependents: [service jboss.deployment.unit."portal-web-1.0-SNAPSHOT.war".component."com.sun.jersey.spi.spring.container.servlet.SpringServlet".START] 
      service jboss.deployment.unit."portal-web-1.0-SNAPSHOT.war".component."org.springframework.web.context.ContextLoaderListener".CREATE (missing) dependents: [service jboss.deployment.unit."portal-web-1.0-SNAPSHOT.war".component."org.springframework.web.context.ContextLoaderListener".START] 
      service jboss.deployment.unit."portal-web-1.0-SNAPSHOT.war".ee.ComponentRegistry (missing) dependents: [service jboss.undertow.deployment.default-server.default-host."/portal-web-1.0-SNAPSHOT".UndertowDeploymentInfoService] 
JBAS014777:   Services which failed to start:      service jboss.persistenceunit."portal-web-1.0-SNAPSHOT.war#OneW2"

Как отключить настольный отдых?

Теги:
spring
hibernate

4 ответа

4
Лучший ответ

Проблема может быть в вашем файле конфигурации hibernate.

Please look into a property hibernate.hbm2ddl.auto

Это может быть одно из этих значений и объяснение для каждого из них.

validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session.

Поэтому в соответствии с вашими потребностями установите свойство в файле

  • 0
    Спасибо, это сработало. Я использовал validate .
2

Попробуйте добавить строку внутри свойства jpaProperties

<prop key="hibernate.hbm2ddl.auto">validate</prop>

Он должен работать.

1

Добавить следующие свойства JPA

<prop key="hibernate.hbm2ddl.auto">update</prop>

Это изменит таблицу в случае изменения структуры таблицы, создаст новую таблицу, в случае, если таблица отсутствует, будет вставляться в таблицу в случае, если присутствует таблица.

1

Я предполагаю, что вы используете Hibernate hbm2ddl.

Затем вы должны использовать значение validate:

 <property name="hibernate.hbm2ddl.auto" value="validate">

См. Документацию Hibernate об этой функции.

  • 0
    Это в файле persistence.xml ?
  • 0
    Да, это обычно там.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню