Проблема при создании bean-объекта entityManagerFactory - PullRequest
0 голосов
/ 27 декабря 2018

Я определил сущности Hibernate в своем проекте, я также создал соответствующие таблицы с помощью функции JBoss Tools «Создать таблицы из сущностей», и все прошло хорошо.У меня правильно настроены таблицы.

Проблема возникает, когда я пытаюсь запустить тест JUnit с целью попробовать функции репозиториев.На данный момент у меня еще не определен запрос.

Трассировка стека следующая:

java.lang.IllegalStateException: Failed to load ApplicationContext
[...]
Caused by: org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'entityManagerFactory' defined in 
class path resource [rootApplicationContext.xml]: Invocation of init 
method failed; nested exception is 
javax.persistence.PersistenceException: [PersistenceUnit: default] 
Unable to build Hibernate SessionFactory; nested exception is 
org.hibernate.exception.SQLGrammarException: Error accessing column 
metadata: movement
[...]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: 
default] Unable to build Hibernate SessionFactory; nested exception 
is org.hibernate.exception.SQLGrammarException: Error accessing 
column metadata: movement
[...]
Caused by: org.hibernate.exception.SQLGrammarException: Error 
accessing column metadata: movement
[...]
Caused by: org.postgresql.util.PSQLException: ERROR: column 
t1.tgconstrname does not exist

Я также попытался переопределить мою сущность MovementEntity.java без результатов.

MovementEntity.java:

@Entity
@Table(name = "movement")
public class MovementEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id")
    private long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "id", referencedColumnName = "id",insertable = false, updatable = false)
    private AccountEntity account;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "id", referencedColumnName = "id",insertable = false, updatable = false)
    private MovementGroupEntity movementGroup;

    @Column(name = "payment_method")
    @Enumerated(EnumType.STRING)
    private PaymentMethodEnum paymentMethod;

    @Column(name = "description", length = 50)
    private String description;

    @Column(name = "amount")
    private double amount;

    @Column(name = "payment_date")
    @Temporal(TemporalType.DATE)
    private Date paymentDate;

    @Column(name = "currency")
    @Enumerated(EnumType.STRING)
    private CurrencyEnum currency;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public AccountEntity getAccount() {
        return account;
    }

    public void setAccount(AccountEntity account) {
        this.account = account;
    }

    public MovementGroupEntity getMovementGroup() {
        return movementGroup;
    }

    public void setMovementGroup(MovementGroupEntity movementGroup) {
        this.movementGroup = movementGroup;
    }

    public PaymentMethodEnum getPaymentMethod() {
        return paymentMethod;
    }

    public void setPaymentMethod(PaymentMethodEnum paymentMethod) {
        this.paymentMethod = paymentMethod;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public double getAmount() {
        return amount;
    }

    public void setAmount(double amount) {
        this.amount = amount;
    }

    public Date getPaymentDate() {
        return paymentDate;
    }

    public void setPaymentDate(Date paymentDate) {
        this.paymentDate = paymentDate;
    }

    public CurrencyEnum getCurrency() {
        return currency;
    }

    public void setCurrency(CurrencyEnum currency) {
        this.currency = currency;
    }

}

AccountEntity.java:

@Entity
@Table(name = "account")
public class AccountEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id")
    private long id;

    @OneToMany(mappedBy = "account", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<MovementEntity> movements;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "id", referencedColumnName = "id")
    private PersonalInformationEntity personalInformation;

    @Column(name = "status", length = 30)
    @Enumerated(EnumType.STRING)
    private AccountStatusEnum accountStatus;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public List<MovementEntity> getMovements() {
        return movements;
    }

    public void setMovements(List<MovementEntity> movements) {
        this.movements = movements;
    }

    public PersonalInformationEntity getPersonalInformation() {
        return personalInformation;
    }

    public void setPersonalInformation(PersonalInformationEntity personalInformation) {
        this.personalInformation = personalInformation;
    }

    public AccountStatusEnum getAccountStatus() {
        return accountStatus;
    }

    public void setAccountStatus(AccountStatusEnum accountStatus) {
        this.accountStatus = accountStatus;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}

MovementGroupEntity.java:

@Entity
@Table(name = "movement_group")
public class MovementGroupEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    @Column(name = "name", length = 30)
    private String name;

    @Column(name = "description", length = 30)
    private String description;

    @OneToMany(mappedBy = "movementGroup", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<MovementEntity> movements;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<MovementEntity> getMovements() {
        return movements;
    }

    public void setMovements(List<MovementEntity> movements) {
        this.movements = movements;
    }

    public static long getSerialversionuid() {
        return serialVersionUID;
    }

}

persistence.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.1"
        xmlns="http://xmlns.jcp.org/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema- 
     instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
        <persistence-unit name="aster.jpa"
            transaction-type="RESOURCE_LOCAL">
            <class>it.manuelgozzi.aster.jpa.entity.AccessDataEntity</class>
            <class>it.manuelgozzi.aster.jpa.entity.AccountEntity</class>
            <class>it.manuelgozzi.aster.jpa.entity.AsterConfigurationEntity</class>
            <class>it.manuelgozzi.aster.jpa.entity.MovementEntity</class>
            <class>it.manuelgozzi.aster.jpa.entity.MovementGroupEntity</class>
            <class>it.manuelgozzi.aster.jpa.entity.PersonalGoalEntity</class>
            <class>it.manuelgozzi.aster.jpa.entity.PersonalInformationEntity</class>
            <properties>
                <property name="javax.persistence.jdbc.url"
                    value="jdbc:postgresql://localhost:3306/aster" />
                <property name="javax.persistence.jdbc.user"
                    value="postgres" />
                <property name="javax.persistence.jdbc.password"
                    value="1234" />
                <property name="javax.persistence.jdbc.driver"
                    value="org.postgresql.Driver" />
                <property name="hibernate.dialect"
                    value="org.hibernate.dialect.PostgreSQLDialect" />
                <!-- <property name="hibernate.hbm2ddl.auto" value="validate" />
                <property name="hibernate.show_sql" value="true" />
                <property name="hibernate.format_sql" value="true" /> -->
            </properties>
        </persistence-unit>
    </persistence>

Spring's rootApplicationContext.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:tx="http://www.springframework.org/schema/tx"
    xmlns:repository="http://www.springframework.org/schema/data/repository"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-2.1.xsd">

    <context:component-scan
        base-package="it.manuelgozzi.aster" />
    <jpa:repositories
        base-package="it.manuelgozzi.aster.jpa.repository"
        entity-manager-factory-ref="entityManagerFactory"
        transaction-manager-ref="transactionManager" />
    <tx:annotation-driven
        transaction-manager="transactionManager" />

    <bean name="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName"
            value="org.postgresql.Driver" />
        <property name="url"
            value="jdbc:postgresql://localhost:3306/aster" />
        <property name="username" value="postgres" />
        <property name="password" value="1234" />
    </bean>

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

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="it.manuelgozzi.aster" />
        <property name="loadTimeWeaver">
            <bean
                class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
        </property>
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    </bean>

    <bean id="jpaVendorAdapter"
        class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="showSql" value="true" />
        <property name="generateDdl" value="true" />
        <property name="databasePlatform"
            value="org.hibernate.dialect.PostgreSQLDialect" />
    </bean>

</beans>

Я не могу понять, в чем проблема.Я прочитал в этой теме , что это может быть ошибкой, но я не нашел дополнительной информации об этом.

Буду признателен за любую дополнительную помощь от вас.

Благодарю за советы, Мануэль.

РЕДАКТИРОВАТЬ:

Я не добавил сюда все сущности в своем посте, которые, по моему мнению, могут быть излишними.Дайте мне знать, если вам нужна дополнительная информация, пожалуйста.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...