我有这些表格:
CREATE TABLE ref.doc (
id serial PRIMARY KEY,
iddoc integer NOT NULL UNIQUE,
docname varchar(254) NOT NULL
);
CREATE TABLE person (
id serial PRIMARY KEY,
name varchar(40) DEFAULT NULL,
doctype integer DEFAULT NULL REFERENCES ref.doc(iddoc)
);
我需要使用Spring构建一个RESTful Web服务,它接收JSON并在经过一些验证后将它们保存到数据库中。例如,iddoc = 2
中有ref.doc
的记录。所以person
的JSON看起来像这样:
{
"name": "John",
"doctype": 2
}
我想做这样的事情:
@RestController
public class PersonController {
@Autowired
PersonRepository personRepository;
@Transactional
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Person add(@RequestBody Person person) {
// some logic
personRepository.saveAndFlush(person);
return person;
}
}
我有这些实体:
@Entity
@Table(schema = "ref")
public class Doc {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private long id;
private Integer iddoc;
private String docname;
...
}
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private long id;
private String name;
@ManyToOne
@JoinColumn(name = "doctype", referencedColumnName = "iddoc", nullable = false)
private Doc doc;
...
}
在这种情况下,doc
中的person
始终是null
,而且它几乎可以理解。但是如何实现我需要的行为?
答案 0 :(得分:0)
你看过这个链接吗?
特别要看一下订单表和客户表之间的关系。
根据我的理解,你需要一个人拥有多份文件。 所以尝试更改定义
private Doc doc;
到
@OneToMany(mappedBy="person", fetch=FetchType.EAGER)
private List<Doc> docs;
并在Doc类中尝试添加:
@ManyToOne(optional=false)
@JoinColumn(name="doctype",referencedColumnName="iddoc")
private Person person;
这应该是实现所需行为的正确方法,而不是100%确定。 这是另一个链接,解释了如何实现所需的解决方案:
答案 1 :(得分:0)
@RestController
public class PersonController {
@Autowired
PersonRepository personRepository;
@Autowired
DocRepository docRepository;
@Transactional
@RequestMapping("/add")
@ResponseBody
public void add(@RequestBody Person person) {
Doc doc=docRepository.findByIddoc(person.getDoc().getIddoc());
if(!(doc==null)){
Person personAdd=new Person();
personAdd.setName("name");
personAdd.setDoc(doc);
personRepository.saveAndFlush(person);
}
}
}
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@JsonIgnore
private long id;
private String name;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "doctype", referencedColumnName = "iddoc", nullable = false)
private Doc doc;
@Entity
@Table(schema = "demo")
public class Doc {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonIgnore
private long id;
private Integer iddoc;
private String docname;