java JPA@OneToMany@manytone双向,集合始终为空
我的@OneToMany@ManyToOne双向关系有问题,每当我查询收藏时,我都会得到一个空的。我在stackoverflow上看到过类似的问题,但不幸的是,到目前为止,non帮助了我
用户模型(OneToMany)
@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.
}
加密SNP模型(多通)
@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>;选择encrypted_snp中的owner_id'返回3行正确的owner_id:
+----------+
| owner_id |
+----------+
| 3 |
| 3 |
| 3 |
+----------+
我希望我已经提供了足够的信息来澄清我的问题。 基本上,我的问题是{user}。getEncryptedSnps()始终返回空集合
共 (0) 个答案