如何从另一个表中获取数据

u2nhd7ah  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(314)
@Entity
@Table(name="driver_duties")
public class Duties{
    private String driverId;
    private String hubName;
    private String vehicleNumber;

// with getter and setters

}

另一张table

@Entity
@Table(name="driver_info")
public class Info{
    private String driverId;
    private String firstName;
    private String lastName;

// with getter and setters

}

我想在driverid的基础上得到表driver\u duties中的firstname和lastname怎么能得到这个。我是jpa新手,我尝试过@onetoone,但无法实现。

ou6hu8tu

ou6hu8tu1#

在类信息中添加职责作为数据成员

@Entity
@Table(name="driver_info")
public class Info{
    private String driverId;
    private String firstName;
    private String lastName;
    private Duties duties;

// with getter and setters

}
eni9jsuy

eni9jsuy2#

理想情况下,您需要以下配置,您应该使用 id 每个实体的属性,

@Entity
@Table(name="driver_duties")
public class Duties{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private String id;

    @Column(name = "hubName")
    private String hubName;

    @Column(name = "vehicleNumber")
    private String vehicleNumber;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "duty_id")
    private Info info;

// with getter and setters

}

@Entity
@Table(name="driver_info")
public class Info{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private String id;

    @Column(name = "firstName")
    private String firstName;

    @Column(name = "lastName")
    private String lastName;

    @OneToOne(mappedBy = "info", cascade = CascadeType.ALL,
    fetch = FetchType.LAZY)
    private Duties duties;

// with getter and setters

}

相关问题