hibernate映射到带有列表的类

时间:2014-10-22 15:14:12

标签: java hibernate

我有3个课程,如下所示。

@Entity
public class Family (  
    @Id
    private String familyName;

    private int size;

    @OneToMany
    protected VehiclesList getVehiclesList()

    // getters and setters
)

public class VehiclesList (
    private List<Vehicle> vehicles;

    @Transient
    private int totalInsuranceCost

    // getters and setters
}

@Entity
public class Vehicle (
    @Id
    private String plateNumber;
    private String model;
    private String color;

    // getters and setters
)

我想创建两个表。第一个是&#34; Family&#34;列为&#34; size&#34;等。这很容易。其次,我想创建一个&#34; Vehicle&#34;关于家庭的表格。该表应包含以下列:     车牌号码     姓     模型     颜色

我希望Family类引用VehiclesList类,以便我可以从VehiclesList类访问信息。 VehiclesList类中的所有数据都不会持久保存到数据库中 - 只有车辆。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

VehicleList不是实体,因此您无法在其上使用OneToMany

totalInsuranceCost不应该是这样的属性,而是更像是服务方法的东西 VehicleService.calculateTotalInsuranceCostForFamily (String familyName)

您的家庭实体将成为:

@Entity
public class Family (  
    @Id
    private String familyName;

    private int size;

    @OneToMany(mappedBy = "family")
    private List<Vehicle> vehicles;

    // getters and setters
)