我正在创建一个MySQL数据库,如下所示: database design
国家和省份表格预先填入了数据。我正在运行应用程序并且可以获得没有问题的东西,并且连接表person_has_address
在获取时也可以工作。
但是,当我使用post插入数据时,我希望能够设置省的ID,并让spring数据jpa只将该数字添加到Address表中的add_pro_id
。例如,当我发布以下json时:
{ "firstName":"bilbo", "lastName":"baggings", "address":{"street":"streetName", "streetNum":3, "zipcode":"1337GG", "city":"TheCity", "province":{"name":"aProvinceName"}} }
jpa应该看到aProvinceName
存在并抓住id
并将其添加到add_pro_id
。
现在它只是在省内插入aProvinceName
作为新值,并将新id
添加到add_pro_id
。
人员班:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="per_id")
private int id;
@Column(name="per_name")
private String firstName;
@Column(name="per_surname")
private String lastName;
@Column(name="per_birth_date")
private String birthDate;
@Column(name="per_fax")
private String fax;
@Column(name="per_phone")
private String phone;
@Column(name="per_email")
private String email;
@OneToOne(optional = false, cascade = CascadeType.ALL)
@JoinTable(name="person_has_address", joinColumns = {@JoinColumn(name="pha_per_id", referencedColumnName = "per_id")}, inverseJoinColumns = {@JoinColumn(name="pha_add_id", referencedColumnName = "add_id")})
private Address address;
// getters and setters
这是人员存储库:
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(@Param("name") String name);
}
这是地址类:
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="add_id")
private int id;
@Column(name = "add_street")
private String street;
@Column(name="add_street_num")
private int streetNum;
@Column(name="add_zip")
private String zipcode;
@Column(name="add_city")
private String city;
@JoinColumn(name="add_pro_id", referencedColumnName = "pro_id")
@ManyToOne(optional=false, cascade = CascadeType.ALL)
private Province province;
// getters and setters
省级:
@Entity
public class Province {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="pro_id")
private int id;
@Column(name="pro_name")
private String name;
@ManyToOne
@JoinColumn(name="pro_cou_id")
private Country country;
// getters and setters
最后是国家级:
@Entity
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="cou_id", insertable = false, updatable = false)
private int id;
@Column(name="cou_name", insertable = false, updatable = false)
private String name;
// getters and setters
我已尝试添加insertable = false
和updatable = false
,但应用程序只会在我的数据库中插入NULL
值。我也试过与@primarykeyjoins
合作,但没有成功。
如果有人知道我应该如何解决这个问题,我将非常感激!
提前致谢。