我的@OneToMany @ManyToOne双向关系存在问题,每当我查询该集合时,我都会得到一个空的。我已经阅读了有关在stackoverflow上发布的类似问题,但遗憾的是到目前为止还没有帮助我。
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@JsonBackReference
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
private Set<EncryptedSnp> encryptedSnps = new HashSet<>();
protected User() {}
public Set<EncryptedSnp> getEncryptedSnps() {
return encryptedSnps;
}
public void setEncryptedSnps(Set<EncryptedSnp> encryptedSnps) {
this.encryptedSnps = encryptedSnps;
}
@Transient
public void addEncryptedSnp(EncryptedSnp encryptedSnp) {
this.encryptedSnps.add(encryptedSnp);
if (encryptedSnp.getOwner() != this) {
encryptedSnp.setOwner(this);
}
}
// ..
// some other non-relevant or straightforward property fields, getters, and setters.
}
@Entity
public class EncryptedSnp {
private long id;
private User owner;
private byte[] value;
protected EncryptedSnp() {}
public EncryptedSnp(BigInteger value, User owner) {
this.value = value.toByteArray();
this.owner = owner;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "encrypted_snp_id")
public long getId() {
return id;
}
@JsonManagedReference
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
public User getOwner() {
return owner;
}
@Column(name = "snp_encrypted", nullable = false, columnDefinition = "blob")
public byte[] getRawValue() {
return rawValue;
}
public void setOwner(User owner) {
this.owner = owner;
}
// ..
// some other non-relevant or straightforward property fields, getters, and setters.
}
@Autowired
private UserRepo userRepo;
@Transactional
public void addSnps() {
User snpTestUser = userRepo.findByUsername("snp_test");
Assert.notNull(snpTestUser);
EncryptedSnp encryptedSnpA = new EncryptedSnp(getRandomBigInteger(), snpTestUser);
EncryptedSnp encryptedSnpB = new EncryptedSnp(getRandomBigInteger(), snpTestUser);
EncryptedSnp encryptedSnpC = new EncryptedSnp(getRandomBigInteger(), snpTestUser);
snpTestUser.addEncryptedSnp(encryptedSnpA);
snpTestUser.addEncryptedSnp(encryptedSnpB);
snpTestUser.addEncryptedSnp(encryptedSnpC);
userRepo.save(snpTestUser);
}
@Transactional
@RequestMapping(value = "user/snp_test/snps", method = RequestMethod.GET)
public ResponseEntity<Set<EncryptedSnp> getEncryptedSnps() {
User snpTestUser = userRepo.findByUsername("snp_test");
Assert.notNull(snpTestUser);
// size is always 0
Assert.isTrue(user.getEncryptedSnps().size() > 0);
// irrelevant
}
PS:'mysql&gt; select encrypted_id from encrypted_snp'返回3行,其中包含正确的owner_id:
+----------+
| owner_id |
+----------+
| 3 |
| 3 |
| 3 |
+----------+
我希望我已经提供了足够的信息来澄清我的问题。 基本上,我的问题是{user} .getEncryptedSnps()总是返回一个空集合。