子对象无法以一对多双向关系保存

时间:2013-10-02 16:48:16

标签: spring hibernate

我与Location和TradeLocation类有一对多的关系。我已尝试过各种替代方法,但仍然在子类(TradeLocation)中插入失败。 以下是我现在获得的代码和堆栈跟踪:

//Parent Class
@Entity
@Table(name="location")
public class Location implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Id
    @GeneratedValue
    private Long id;


    private String name;
    private Long stateId;
    private Long districtId;
    private Long cityId;
    private Long zoneId;
    @Column(name="yearEstablishment")
    private String yearOfEstablishment;

    @OneToMany(fetch = FetchType.LAZY,mappedBy="location")
    @Cascade({CascadeType.SAVE_UPDATE})
    @Column(nullable = false)
    private Set<TradeLocation>tradeLocation=new HashSet<TradeLocation>(0);

    /*getter and setter*/
}

//Child class
@Entity
@Table(name = "trade_location")
public class TradeLocation implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;


    /*@ManyToOne(fetch=FetchType.EAGER)*/
    @ManyToOne
    @JoinColumn(name="tradeId")
    private Trade trade;

    @ManyToOne(fetch=FetchType.EAGER)
    /*@Cascade({org.hibernate.annotations.CascadeType.ALL})*/
    @JoinColumn(name="locationId",nullable = false)
    private Location location;

    @Enumerated(EnumType.STRING)
    private TradeStatus status;

    //getter and setter
}

堆栈追踪:

Hibernate: insert into location (cityId, districtId, name, stateId, yearEstablishment, zoneId)  values (?, ?, ?, ?, ?, ?)
Hibernate: insert into trade_location (locationId, status, tradeId) values (?, ?, ?)
[ WARN] [http-bio-8080-exec-2 10:07:56] (SqlExceptionHelper.java:logExceptions:143) SQL Error: 1048, SQLState: 23000
[ERROR] [http-bio-8080-exec-2 10:07:56] (SqlExceptionHelper.java:logExceptions:144) Column 'locationId' cannot be null

//Insertion Code :
Session session =   sessionFactory.getCurrentSession();
session.saveOrUpdate(location);

0 个答案:

没有答案