我有两张桌子vehicle
和vehicle_image
。车辆表包含车辆的所有主数据,vehicle_image表包含图像的元信息和图像的Base64编码的字符串。在车辆上可能有0或更多图像。
现在,当我查询车辆对象时,我希望该对象包含来自vehicle_image表的信息。
我对JPA很新,我能找到的例子似乎总是从另一个表中读取一个值,而不是列表。
将属性添加到包含图像数据的车辆对象的最简单方法是什么?
@Entity
@XmlRootElement(name = "vehicle")
public class Vehicle {
@Id
private String vin;
private String commission;
@Column(name="swiss_type_number")
private String swissTypeNumber;
@Column(name="sale_type")
private String saleType;
@Column(name="exterior_color")
private String exteriorColor;
@Column(name="interior_color")
private String interiorColor;
private String remarks;
@Column(name="additional_title")
private String additionalTitle;
@Column(name="added_value_description")
private String addedValueDescription;
@Column(name="first_registration")
private String firstRegistration;
private String guaranty;
@Column(name="last_inspection")
private String lastInspection;
private int dealer;
private int mileage;
private int price;
private int seats;
@Column(name="model_year")
private int modelYear;
@Column(name="car_damaged_in_accident")
private boolean carDamagedInAccident;
private boolean imported;
// List of images
List<VehicleImage> vehicleImages; // Something like this would be nice
}
答案 0 :(得分:1)
您在此处拥有one-to-may关系,您可以使用:
@OneToMany
List<VehicleImage> vehicleImages;
参考javadoc获取它可能采用的属性,并根据您的表定义添加它们。
Here你可以找到一些如何使用它的例子。
答案 1 :(得分:1)
JPA支持实体之间的关联。你需要的是@OneToMany
如果您的vehicle_image' table contains column
vehicle_id you will need following mapping in
车辆类:
@Entity
@Table(name = "VEHICLE")
@XmlRootElement(name = "vehicle")
public class Vehicle {
// other fields here
@OneToMany(mappedBy = "vehicle")
Set<VehicleImage> vehicleImages;
}
此问题也在VehicleImage
@Entity
@Table(name = "VEHICLE_IMAGE")
public class VehicleImage{
// other fields here
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
@JoinColumn(name="VEHICLE_ID", referencedColumnName = "ID")
Vehicle vehicle;
}
另外,您应该更好地使用Set
进行JPA中的集合映射,但这是一个不同的主题