【发布时间】:2019-02-19 13:01:12
【问题描述】:
我用 Java Spring 和 Hibernate 创建了一个数据库。有一个责任实体和一个帐户实体,它们与 OneToOne 关系链接。 这是我的代码:
REST 控制器:
@RestController
@RequestMapping("/test")
public class test {
@Autowired
private final ResponsableDBRepository responsableDBRepository;
public test(ResponsableDBRepository responsableDBRepository){
this.responsableDBRepository = responsableDBRepository;
}
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> insert(@RequestBody ResponsableEntity responsableEntity) {
responsableDBRepository.save(responsableEntity);
return ResponseEntity.accepted().build();
}
}
责任实体:
@Entity
@Table(name = "responsable")
public class ResponsableEntity {
/**
* Id of the resident
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* First name of the responsable
*/
@Column(nullable=false)
private String firstName;
/**
* Lst name of the responsable
*/
@Column(nullable=false)
private String lastName;
/**
* Account id of the responsable
*/
//@Column(nullable=false)
@OneToOne
@JoinColumn(name = "account", referencedColumnName = "id")
private AccountEntity account;
账户实体:
@Entity
@Table(name = "account")
public class AccountEntity {
/**
* Id of the acount
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* Username of the acount
*/
@Column(nullable=false)
private String username;
/**
* Password of the account
*/
@Column(nullable=false)
private String password;
我想要做的是向我的控制器 (/test) 发送一个 POST HTTP 请求并发送一个 JSON 来创建一个帐户并负责并将两者链接到数据库中
这是我为学校准备的一个项目,这是我第一次使用 Spring 和 Hibernate,所以我无法说出它是否可能以及如果可能的话如何编写 JSON
我已经尝试了一点,但没有任何效果,我在互联网上找不到答案
提前感谢您的回答!
【问题讨论】:
-
您可以创建一个包装器对象来包装两者,并将该对象作为 JSON 正文发送。
-
是的,最好的方法是创建一个包装器 DTO(数据传输对象),然后从那里开始工作。
-
他为什么需要一个包装对象?一个对象已经包含另一个对象。
标签: java json spring hibernate rest