空值插入hibernate中的一对多关系映射

时间:2014-03-27 16:36:01

标签: hibernate

当我运行此代码并尝试使用某些车辆保存用户信息类时。值正确地插入到用户信息表中但在车辆表空值中插入外键列

/ **用户信息类 * /

import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;    
import org.hibernate.annotations.Cascade;

@Entity
public class Userinformation {

    int id;
    String username;
    Set<Vehicle> vehicles = new HashSet<Vehicle>();



    public Userinformation() {
    }

    public Userinformation(int id) {
        this.id = id;
    }

    public Userinformation(int id,String username,Set<Vehicle> vehicles){

        this.id=id;
        this.username=username;
        this.vehicles=vehicles;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "userinformation")
    public Set<Vehicle> getVehicles() {
        return vehicles;
    }

    public void setVehicles(Set<Vehicle> vehicles) {
        this.vehicles = vehicles;
    }

}

/ * ** * ** 车辆类 * ** * ** * *** /

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;


@Entity
public class Vehicle {

    int id;
    String vehicleName;
    Userinformation userinformation;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    public int getId() {
        return id;
    }

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

    public String getVehicleName() {
        return vehicleName;
    }

    public void setVehicleName(String vehicleName) {
        this.vehicleName = vehicleName;
    }


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id",referencedColumnName="id")
    public Userinformation getUserinformation() {
        return userinformation;
    }



    public void setUserinformation(Userinformation userinformation) {
        this.userinformation = userinformation;
    }

}

/ * ** * ** 输出 * ** * < / EM> ** * * /

用户信息表

id |用户名|

1 |魔术|

车辆表

id | vehicleName | user_id |

1 |宝马| NULL | 2 |奥迪|空|

0 个答案:

没有答案