如何将Spring Data JPA与Hibernate 5.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
}
实例源自JAXB unmarshaller,出于我们的目的,我们假设:
public Person data(String name, Integer zip, String city) {
Person person = new Person();
person.setName(name);
Address address = new Address();
address.setZip(zip);
address.setCity(city);
person.setAddress(address);
return 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);
当然,代码因唯一约束违规而失败,所以我想知道是否有某种方式我可以为JPA指定业务键,以便将我的实体与现有的行匹配数据库(例如zip
)。