Java 让Spring数据JPA查找匹配用于级联的实体

Java 让Spring数据JPA查找匹配用于级联的实体,java,jpa,spring-data-jpa,Java,Jpa,Spring Data Jpa,如何使用SpringDataJPA和Hibernate5.0.12作为供应商,将现有数据库条目匹配到非托管实体上进行级联 假设我有这样的实体: @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; @ManyToOne(cascade = CascadeType

如何使用SpringDataJPA和Hibernate5.0.12作为供应商,将现有数据库条目匹配到非托管实体上进行级联

假设我有这样的实体:

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;

    @ManyToOne(cascade = CascadeType.ALL)
    private Address address;
}

@Entity
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(unique = true)
    private Integer zip;
    private String city;
}

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
    // implementation provided by Spring Data JPA
}
现在,我希望此代码按上述方式工作:

Person p1 = data("Alice", 12345, "Berlin");
Person p2 = data("Bob", 12345, "Berlin");

// create a row in person table and create a row in address table
personRepository.save(p1);

// this should only create a row in person 
// and assign existing address entity reference to it
personRepository.save(p2);

当然,由于一个唯一的约束冲突,代码会失败,因此我想知道是否有某种方法可以为JPA指定业务密钥,以便将我的实体与数据库中的现有行(例如
zip
)相匹配。

我提出的唯一解决方案是更改数据方法,以实际检查地址是否已经在db中,检索地址并在person对象(如果存在)中设置它,或者设置一个新的地址对象(否则)。不幸的是,我从
Jaxb2Marshaller\35; unmarshal
中检索数据,因此我认为这是不可能的。因此,在jpa repo上创建一个具有相同方法名save的服务,该服务在保存person之前检查并替换地址。
Person p1 = data("Alice", 12345, "Berlin");
Person p2 = data("Bob", 12345, "Berlin");

// create a row in person table and create a row in address table
personRepository.save(p1);

// this should only create a row in person 
// and assign existing address entity reference to it
personRepository.save(p2);