0

У меня есть проект на spring mvc c использованием хибернейта. В нем есть две связанные таблицы EstateEntity и UserEntity.

EstateEntity.java

package by.specific.entity;

import javax.persistence.*;

@Entity
@Table(name = "estate", schema = "courseProject", catalog = "")
public class EstateEntity {
    private int id;
    private String loginIndef;
    private String price;
    private String floor;
    private Integer roomCount;
    private Integer area;
    private String other;
    private String urlPicture;
    private String typeEstate;
    private String country;
    private String name;
    private UserEntity userByLoginIndef;

    @Id
    @Column(name = "id", nullable = false)
    public int getId() {
        return id;
    }

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

    @Basic
    @Column(name = "loginIndef", nullable = false, length = 255)
    public String getLoginIndef() {
        return loginIndef;
    }

    public void setLoginIndef(String loginIndef) {
        this.loginIndef = loginIndef;
    }

    @Basic
    @Column(name = "price", nullable = false, length = 255)
    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    @Basic
    @Column(name = "floor", nullable = true, length = 45)
    public String getFloor() {
        return floor;
    }

    public void setFloor(String floor) {
        this.floor = floor;
    }

    @Basic
    @Column(name = "roomCount", nullable = true)
    public Integer getRoomCount() {
        return roomCount;
    }

    public void setRoomCount(Integer roomCount) {
        this.roomCount = roomCount;
    }

    @Basic
    @Column(name = "area", nullable = true)
    public Integer getArea() {
        return area;
    }

    public void setArea(Integer area) {
        this.area = area;
    }

    @Basic
    @Column(name = "other", nullable = true, length = 1800)
    public String getOther() {
        return other;
    }

    public void setOther(String other) {
        this.other = other;
    }

    @Basic
    @Column(name = "urlPicture", nullable = true, length = 450)
    public String getUrlPicture() {
        return urlPicture;
    }

    public void setUrlPicture(String urlPicture) {
        this.urlPicture = urlPicture;
    }

    @Basic
    @Column(name = "typeEstate", nullable = false, length = 45)
    public String getTypeEstate() {
        return typeEstate;
    }

    public void setTypeEstate(String typeEstate) {
        this.typeEstate = typeEstate;
    }

    @Basic
    @Column(name = "country", nullable = false, length = 45)
    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Basic
    @Column(name = "name", nullable = true, length = 256)
    public String getName() {
        return name;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        EstateEntity that = (EstateEntity) o;

        if (id != that.id) return false;
        if (loginIndef != null ? !loginIndef.equals(that.loginIndef) : that.loginIndef != null) return false;
        if (price != null ? !price.equals(that.price) : that.price != null) return false;
        if (floor != null ? !floor.equals(that.floor) : that.floor != null) return false;
        if (roomCount != null ? !roomCount.equals(that.roomCount) : that.roomCount != null) return false;
        if (area != null ? !area.equals(that.area) : that.area != null) return false;
        if (other != null ? !other.equals(that.other) : that.other != null) return false;
        if (urlPicture != null ? !urlPicture.equals(that.urlPicture) : that.urlPicture != null) return false;
        if (typeEstate != null ? !typeEstate.equals(that.typeEstate) : that.typeEstate != null) return false;
        if (country != null ? !country.equals(that.country) : that.country != null) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (loginIndef != null ? loginIndef.hashCode() : 0);
        result = 31 * result + (price != null ? price.hashCode() : 0);
        result = 31 * result + (floor != null ? floor.hashCode() : 0);
        result = 31 * result + (roomCount != null ? roomCount.hashCode() : 0);
        result = 31 * result + (area != null ? area.hashCode() : 0);
        result = 31 * result + (other != null ? other.hashCode() : 0);
        result = 31 * result + (urlPicture != null ? urlPicture.hashCode() : 0);
        result = 31 * result + (typeEstate != null ? typeEstate.hashCode() : 0);
        result = 31 * result + (country != null ? country.hashCode() : 0);
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }

    @ManyToOne
    @JoinColumn(name = "loginIndef", referencedColumnName = "login", nullable = false)
    public UserEntity getUserByLoginIndef() {
        return userByLoginIndef;
    }

    public void setUserByLoginIndef(UserEntity userByLoginIndef) {
        this.userByLoginIndef = userByLoginIndef;
    }
}

UserEntity.java

package by.specific.entity;

import javax.persistence.*;
import java.util.Collection;

@Entity
@Table(name = "user", schema = "courseProject", catalog = "")
public class UserEntity {
    private String login;
    private String password;
    private String email;
    private String role;
    private String bonus;
    private Collection<EstateEntity> estatesByLogin;

    @Id
    @Column(name = "login", nullable = false, length = 255)
    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    @Basic
    @Column(name = "password", nullable = false, length = 255)
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "email", nullable = false, length = 45)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Basic
    @Column(name = "role", nullable = false, length = 45)
    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    @Basic
    @Column(name = "bonus", nullable = true, length = 45)
    public String getBonus() {
        return bonus;
    }

    public void setBonus(String bonus) {
        this.bonus = bonus;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserEntity that = (UserEntity) o;

        if (login != null ? !login.equals(that.login) : that.login != null) return false;
        if (password != null ? !password.equals(that.password) : that.password != null) return false;
        if (email != null ? !email.equals(that.email) : that.email != null) return false;
        if (role != null ? !role.equals(that.role) : that.role != null) return false;
        if (bonus != null ? !bonus.equals(that.bonus) : that.bonus != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = login != null ? login.hashCode() : 0;
        result = 31 * result + (password != null ? password.hashCode() : 0);
        result = 31 * result + (email != null ? email.hashCode() : 0);
        result = 31 * result + (role != null ? role.hashCode() : 0);
        result = 31 * result + (bonus != null ? bonus.hashCode() : 0);
        return result;
    }

    @OneToMany(mappedBy = "userByLoginIndef")
    public Collection<EstateEntity> getEstatesByLogin() {
        return estatesByLogin;
    }

    public void setEstatesByLogin(Collection<EstateEntity> estatesByLogin) {
        this.estatesByLogin = estatesByLogin;
    }
}

Вот мой Dispacher:

    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="by.specific"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- Database Information -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/courseProject"/>
        <property name="username" value="root"/>
        <property name="password" value="Liz54387621"/>
    </bean>

    <!-- Hibernate 4 SessionFactory Bean definition -->
    <bean id="hibernate4AnnotatedSessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="annotatedClasses">
            <list>
               <value>by.specific.entity.EstateEntity</value>
                <value>by.specific.entity.UserEntity</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/MySQL</prop>
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
            </props>
        </property>
    </bean>

    <!--BookDao and BookService beans-->
    <bean id="estateDao" class="by.specific.dao.EstateDaoImpl">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </bean>
    <bean id="estateService" class="by.specific.service.EstateServiceImpl">
        <property name="estateDao" ref="estateDao"/>
    </bean>
    <bean id="UsersDao" class="by.specific.dao.UsersDaoImpl">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </bean>
    <bean id="UserSService" class="by.specific.service.UsersServiceImpl">
        <property name="UsersDao" ref="UsersDao"/>
    </bean>

    <context:component-scan base-package="by.specific"/>

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

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </bean>

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/css/**" location="/css/"/>
</beans>

Не подскажите, по какой причине может быть эта ошибка?

Вот код ошибки:

BeanCreationException: Error creating bean with name 'usersController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method,
BeanCreationException: Could not autowire method: public void by.specific.controller.UsersController.setTopService(by.specific.service.UsersService),
Error creating bean with name 'UserSService' defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]:,
Error creating bean with name 'UsersDao' defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]: Cannot resolve reference to bean 'hibernate4AnnotatedSessionFactory',
Error creating bean with name 'hibernate4AnnotatedSessionFactory' defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]: Invocation of init method failed;,
MappingException: Repeated column in mapping for entity: by.specific.entity.EstateEntity column: loginIndef (should be mapped with insert="false" update="false")

1 ответ 1

2

Во-первых, user является зарезервированным словом в SQL и не может использоваться как имя таблицы или поля. Измените имя таблицы:

@Entity
@Table(name = "users", schema = "courseProject", catalog = "")
public class UserEntity {
    ...
}

Во-вторых, в ошибке написано, что колонка loginIndef объявлена дважды, один раз как private String loginIndef и ещё один как @JoinColumn(name = "loginIndef"). Либо вовсе уберите поле loginIndef, либо добавьте в аннотацию @JoinColumn пару атрибутов - insertable=false и updatable=false.

1
  • Я исправил как вы сказали и мне помогло, спасибо большое!
    – Alikevich
    22 апр 2018 в 10:10

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.