【发布时间】:2017-02-02 20:16:28
【问题描述】:
我有一个 postgres 数据库,我正在尝试使用 Spring Boot 制作一个简单的 REST 服务。我的 jpa 多对多关系有问题。
个人实体:
@Entity
@Table(name = "person", schema = "persons")
public class Person implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String email;
@Column
private Integer age;
@ManyToOne
@JoinColumn(name = "country_id", referencedColumnName = "id")
private Country countryOfBirth;
@ManyToMany
@JoinTable(
name="persons_countries_residence",
joinColumns=@JoinColumn(name="person_id", referencedColumnName="id"),
inverseJoinColumns=@JoinColumn(name="country_id", referencedColumnName="id"))
private List<Country> countriesOfResidence;
// getters and setters and to String method overriden
}
国家实体:
@Entity
@Table(name = "country", schema = "persons")
public class Country implements Serializable {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column(name = "country_name")
private String name;
@Column(name = "country_code")
private String code;
// getters and setters and to String method overriden
}
postgres 架构如下:
人员表:
CREATE TABLE persons.person
(
id serial NOT NULL,
name character varying(50) NOT NULL,
email character varying(40) NOT NULL,
age integer,
country_id serial NOT NULL,
CONSTRAINT id PRIMARY KEY (id),
CONSTRAINT country_id FOREIGN KEY (id)
REFERENCES persons.country (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
国家表:
CREATE TABLE persons.country
(
id serial NOT NULL,
country_name character varying(45) NOT NULL,
country_code character varying(10) NOT NULL,
CONSTRAINT country_id PRIMARY KEY (id)
)
加入表:
CREATE TABLE persons.persons_countries_residence
(
person_id integer NOT NULL,
country_id integer NOT NULL,
CONSTRAINT person_country_id PRIMARY KEY (person_id, country_id),
CONSTRAINT persons_countries_residence_country_id_fkey FOREIGN KEY (country_id)
REFERENCES persons.country (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION,
CONSTRAINT persons_countries_residence_person_id_fkey FOREIGN KEY (person_id)
REFERENCES persons.person (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
当我进行 HTTP 方法调用时,我没有得到居住国家/地区。
服务代码:
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public List<Person> getAllPersons() {
retutn jpaPersonRepository.findAll();
}
任何帮助表示赞赏。
【问题讨论】:
标签: spring postgresql hibernate jpa