每当我创建新商家时,我都会尝试保存公司的董事名单,因此我分别在Director和Merchant之间建立了@ManyToOne关系。
到目前为止,我在设置POST时设法保存了导演和商家列表。但是当我做GET请求时我没有找回导演,列表又回来了。当我签入数据库时,加入列为空,如图所示,但其余数据存在。我该如何解决这个问题?
这是我的代码:
Director.java
@Entity
@Table(name = "Directors")
public class Director {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long directorID;
@Cascade({org.hibernate.annotations.CascadeType.ALL})
@ManyToOne
@JoinColumn(name = "merchantNumber")
private Merchant merchant;
@NotBlank
private String name;
@NotBlank
private String surname;
public Director() {
}
public Director(long directorID, Merchant merchant, String name, String surname) {
this.directorID = directorID;
this.merchant = merchant;
this.name = name;
this.surname = surname;
}
...
Getters and setters
DirectorRepository.java
public interface DirectorRepository extends CrudRepository<Director, String> {
}
Merchant.java
public class Merchant {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int merchantNumber;
@NotBlank
private String merchantID;
@NotBlank
private String businessName;
@Cascade({org.hibernate.annotations.CascadeType.ALL})
@OneToMany(mappedBy = "merchant")
private List<Director> directors;
@NotBlank
private String userName;
public Merchant(int merchantNumber, String merchantID, String businessName, List<Director> directors, String userName ) {
this.merchantNumber = merchantNumber;
this.merchantID = merchantID;
this.businessName = businessName;
this.directors = directors;
this.userName = userName;
}
...
Getter and setters
MerchantService.java
public ResponseMerchantQuery createMerchant(Merchant merchant) {
if( merchant == null || merchant.getMerchantID()== null){
throw new ResourceNotFoundException("Empty", "Missing Data Exception");
} else {
merchant.setPassword(passwordEncoder.encode(merchant.getPassword()));
merchantRepository.save(merchant);
String merchantNum = Long.toString(merchant.getMerchantNumber());
return new ResponseMerchantQuery(merchantNum, "Merchant Created Successfully");
}
}
MerchantController.java
@RequestMapping(method = RequestMethod.POST, value = "/api/merchants")
public ResponseMerchantQuery createMerchant(@Valid @RequestBody Merchant merchant){
System.out.println("size of merchnat " + merchant.getDirectors().size());
return merchantService.createMerchant(merchant);
}