在多对多关系中有两个类,Person 和 Vehicle。如果创建了新人员或更新了现有人员的记录(例如添加了车辆记录),则最好使用现有的车辆记录(如果存在)。
问题是如何实现它。插入或更新之前的查询不是一个选项,因为有许多线程可以更新或插入。
此时应用程序检查唯一约束异常,当它被捕获时,新的现有车辆对象被替换为“注册”列从数据库中查询的对象。这个解决方案正在工作,但它似乎有点笨拙,因为必须为每个车辆记录创建一个单独的会话。
有什么方法可以通过休眠注释来实现所需的行为?还是完全不同的解决方案?谢谢。
@Entity
@Table(name="PERSON", uniqueConstraints = { @UniqueConstraint(columnNames = "name", name="NAME_KEY") })
public class Person implements Serializable {
private static final long serialVersionUID = 3507716047052335731L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="PersonIdSeq")
@SequenceGenerator( name = "PersonIdSeq", sequenceName="PERSON_ID_SEQ")
private Long id;
@Index(name="PERSON_NAME_IDX")
private String name;
@ManyToMany(targetEntity=Vehicle.class, cascade={CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name="PERSON_VEHICLE_LNK", joinColumns=@JoinColumn(name="PERSON_ID"),inverseJoinColumns=@JoinColumn(name="VEHICLE_ID"),
uniqueConstraints = { @UniqueConstraint(columnNames = {"PERSON_ID", "VEHICLE_ID"}, name="person_vehicle_lnk_key")})
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="PersonVehicleLnkIdSeq")
@SequenceGenerator(name = "PersonVehicleLnkIdSeq", sequenceName="PERSON_VEHICLE_LNK_ID_SEQ")
@CollectionId(columns = @Column(name="ID"), type=@Type(type="long"), generator = "PersonVehicleLnkIdSeq")
private List<Vehicle> vehicle = new ArrayList<>();
...
@Entity
@Table( name = "VEHICLE", uniqueConstraints = {@UniqueConstraint(columnNames="registration", name="REGISTRATION_KEY")} )
public class Vehicle implements Serializable {
private static final long serialVersionUID = -5592281235230216382L;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="VehicleIdSeq")
@SequenceGenerator( name = "VehicleIdSeq", sequenceName="VEHICLE_ID_SEQ")
private Long id;
@Index(name="REGISTRATION_IDX")
private String registration;
...