如何在hibernate中维护外键关系

时间:2017-09-18 10:01:08

标签: java spring hibernate

我有两个类,我希望它们之间有一对多关系,例如:

Home(id<int>, rooms<string>)

Vehicle(id<int>, home_id<int>, name<string>) 

我需要使用HomeVehicleHome.idvehicle.home_id课程之间建立关系。

请建议我在这里使用CURD操作实现REST服务的任何示例。

1 个答案:

答案 0 :(得分:1)

  

我需要使用HomeVehicleHome.id类之间建立关系   和vehicle.home_id

您的实体应如下所示:

车辆实体

@Entity
@Table(name = "vehicle", catalog = "bd_name", schema = "schema_name")
@XmlRootElement
public class Vehicle implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    @JoinColumn(name = "home_id", referencedColumnName = "id")
    @ManyToOne
    private Home homeId;

    //constructor getter & setters

}

主页实体

@Entity
@Table(name = "home", catalog = "bd_name", schema = "schema_name")
@XmlRootElement
public class Home implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "room")
    private Character room;
    @OneToMany(mappedBy = "homeId")
    private List<Vehicle> vehicleList;

    //constructor getter & setters
}