简体   繁体   中英

How to maintain foreign key relationship in hibernate

I have two classes and I want to have a one to many relation between them, for eg:

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

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

I need to have a relation between Home and Vehicle class using Home.id and vehicle.home_id .

Please suggest any example which I can use here for CURD operation to implement REST service.

I need to have a relation between Home and Vehicle class using Home.id and vehicle.home_id .

Your entities should look like this :

Vehicle Entity

@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

}

Home Entity

@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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM