Hibernate请求处理失败

时间:2015-03-18 10:34:13

标签: java spring hibernate spring-mvc jpa

我正在向城市插入hv多对一映射的用户。然后城市hv manytone映射到国家。因此,当我插入具有重复城市或国家/地区的用户时,它会抛出异常。

@Entity
@Table(name = "users")
@XmlRootElement
public class User implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -2095697913583686677L;

    private String firstname;

    private String lastname;

    private String dob;
    private long mobile;
    private String email;
    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    @JoinColumn(name = "city_name", nullable = false)
    private City city;
    private String country;
    private String password;
    private Date createdTime;
    private Date lastLoggedIn;
    private int rating;
    @Id
    private int id;

    public int getId() {
        return id;
    }

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

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public long getMobile() {
        return mobile;
    }

    public void setMobile(long mobile) {
        this.mobile = mobile;
    }

    public String getEmail() {
        return email;
    }

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

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

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

    public String getPassword() {
        return password;
    }

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

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    public Date getLastLoggedIn() {
        return lastLoggedIn;
    }

    public void setLastLoggedIn(Date lastLoggedIn) {
        this.lastLoggedIn = lastLoggedIn;
    }

    public int getRating() {
        return rating;
    }

    public void setRating(int rating) {
        this.rating = rating;
    }

    public String toString() {
        return "Name = " + firstname + ",Mobile = " + mobile + ",Email = "
                + email + ",City = " + city + ",Country = " + country
                + ", TimeCreated = " + createdTime;
    }

}

@Entity
@Table(name = "city")
public class City {

    @Id
    @GeneratedValue
    private int id;

    @Column(name = "city_name", unique = true, nullable = false, length = 40)
    private String cityName;

    @ManyToOne
    @Cascade(CascadeType.SAVE_UPDATE)
    @JoinColumn(name = "country_name", nullable = false)
    private Country countryName;

    @OneToMany
    @Cascade(CascadeType.SAVE_UPDATE)
    @JoinColumn(name = "city_name")
    private List<User> users;

    public List<User> getStockDailyRecords() {
        return this.users;
    }

    public int getId() {
        return id;
    }

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

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public Country getCountryName() {
        return countryName;
    }

    public void setCountryName(Country countryName) {
        this.countryName = countryName;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

}



@Entity
@Table(name = "country")
public class Country {

    @Id
    @GeneratedValue
    private int id;

    @Column(name = "country_name", unique = true, nullable = false, length = 40)
    private String countryName;

    @OneToMany
    @JoinColumn(name = "country_name")
    private List<City> citys;

    public int getId() {
        return id;
    }

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

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    public List<City> getCitys() {
        return citys;
    }

    public void setCitys(List<City> citys) {
        this.citys = citys;
    }

}

Hibernate Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing: com.shubh.model.User.city -> com.shubh.model.City; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing

弹簧配置: -

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

    <context:component-scan base-package="com.shubh" />
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

<!--    <bean id="mysqldataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"> -->
<!--        <property name="url" value="jdbc:mysql://localhost:3306/apu"></property> -->
<!--        <property name="user" value="root"></property> -->
<!--        <property name="password" value="admin"></property> -->
<!--    </bean> -->

    <bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.shubh.model" />
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         </props>
      </property>
   </bean>

   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/apu" />
      <property name="username" value="root" />
      <property name="password" value="admin" />
   </bean>

   <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="myEmf" />
   </bean>
   <tx:annotation-driven />

   <bean id="persistenceExceptionTranslationPostProcessor"
      class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
    <jpa:repositories base-package="com.shubh.repository"/>



</beans>

2 个答案:

答案 0 :(得分:0)

我没有看到保存对象的代码..但是从异常堆栈中我可以看到你在保存城市之前试图保存人。

答案 1 :(得分:0)

这是错误org.hibernate.TransientPropertyValueException: object references an unsaved transient.

当你试图坚持父对象并且你的孩子不是持久存在时,它会出现,所以在你的情况下,请保存第一个国家,城市,然后将其设置为用户对象,然后保存用户对象。

在hibernate中保存对象有多种方法取决于您使用的

saveOrUpdate();
update();
save();
persist();
merge();

有关详细信息,请访问http://www.journaldev.com/3481/hibernate-save-vs-saveorupdate-vs-persist-vs-merge-vs-update-explanation-with-examples