Java 与联接表的一对多关系:未持久化关系
我使用HibernateJPA注释,至于存储库,我使用SpringJPA 我有以下两个实体:Java 与联接表的一对多关系:未持久化关系,java,hibernate,jpa,spring-data-jpa,Java,Hibernate,Jpa,Spring Data Jpa,我使用HibernateJPA注释,至于存储库,我使用SpringJPA 我有以下两个实体: @Entity @Table(name = "idn_organization") @Audited public class Organization extends UuidBasedEntity { @Column(name = "full_name", length = 64, nullable = false) private String fullName; @On
@Entity
@Table(name = "idn_organization")
@Audited
public class Organization extends UuidBasedEntity {
@Column(name = "full_name", length = 64, nullable = false)
private String fullName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinTable(
name = "idn_organization_address",
joinColumns = @JoinColumn(name = "organization_id"),
inverseJoinColumns = @JoinColumn(name = "address_id")
)
private Set<Address> addresses;
@Column(name = "phone_number", length = 12, nullable = true)
private String phoneNo;
@Column(name = "registered_date", nullable = true)
private Date registeredDate;
@Column(name = "social_security", length = 9, nullable = true)
private String socialSecurity;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Set<Address> getAddresses() {
return addresses != null ? addresses : new HashSet<Address>();
}
public void setAddresses(Set<Address> addresses) {
if (this.addresses == null)
this.addresses = new HashSet<>();
this.addresses.clear();
if (addresses != null)
this.addresses.addAll(addresses);
}
如前所述,我的存储库是:
public interface OrganizationRepository extends JpaRepository<Organization, String>, JpaSpecificationExecutor<Organization> {
}
每当我调用save方法时,组织就会被持久化,它们各自表中的地址也会被持久化。。。但是联接表条目不是!因此,我获得了一个新的组织,一个新的地址,但它们之间没有联系。那么我做错了什么?显然,当我试图以某种方式编辑组织时,也会发生这种情况 问题出在我的服务中,因为我有注释:
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
因为我是通过web流管理事务的,所以它们从未提交。所以我在persist方法中添加了
@Transactional
,这就解决了它。您也可以删除readOnly=true
部分,但我没有删除,因为有一些获取方法我不想公开。以下是您的答案:。顺便说一句,FetchType.EAGER是默认行为,因此不需要显式指定它。我建议您使用FetchType.LAZY
而不是detadumm,请记住,我在地址
下没有对组织
的反向引用,因此它是单向的。我添加了一个addAddress
方法,问题仍然存在。另外,我使用的是一个joinTable
,而不是jointcolumn
。哦,它是一个joinTable
,所以它是manytomy
关系,并且总是双向的。这是一个与联接表的一对多关系。。。
@Service("identityService")
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
public class IdentityServiceImpl implements IdentityService {
private static Logger logger = LoggerFactory.getLogger(IdentityServiceImpl.class);
@Autowired
private OrganizationRepository organizationRepository;
@Override
public void persistOrganization(Organization organization) {
organizationRepository.save(organization);
if (logger.isDebugEnabled()) {
logger.debug("Organization [" +
organization.getUuid() + " - " +
organization.getFullName() + "] created or updated.");
}
}
}
@Transactional(readOnly = true, propagation = Propagation.REQUIRED)