与连接表的一对多关系:关系不被持久化

时间:2014-09-15 18:54:42

标签: java hibernate jpa spring-data-jpa

我正在使用hibernate JPA注释,至于存储库,我正在使用Spring JPA

我有以下两个实体:

@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);
    }

@Entity
@Table(name = "cmn_address")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Audited
public class Address extends AutoIdBasedEntity {

    @Valid
    @NotNull(message = "{address.type.notNull}")
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "type_code")
    @ForeignKey(name = "FK_address_address_type")
    @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
    private AddressType type;

    @NotNull(message = "{address.line1.notNull}")
    @Column(name = "address_line_1", length = 256, nullable = true)
    private String addressLine1;

    @Column(name = "address_line_2", length = 128, nullable = true)
    private String addressLine2;

    @Column(name = "address_line_3", length = 128, nullable = true)
    private String addressLine3;

    @Valid
    @NotNull(message = "{address.town.notNull}")
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "city_id")
    @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
    private Town city;

    @NotNull(message = "{address.state.notNull}")
    @Size(min = 2, max = 2, message = "{address.state.notEmpty}")
    @Column(name = "state_code")
    private String state;

    //@NotNull(message = "{address.zip.notNull}")
    // TODO Not all DTOP Results match
    // @Pattern(regexp = "\\d{5}(-\\d{4})?", message = "{address.zip.notValid}")
    @Column(name = "postal_code", length = 32, nullable = true)
    private String postalCode;

    @Valid
    @NotNull(message = "{address.country.notNull}")
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "country_code")
    @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
    private Country country;

如上所述,我的存储库是:

public interface OrganizationRepository extends JpaRepository<Organization, String>, JpaSpecificationExecutor<Organization> {
}

我遇到的问题是保存在我的服务中的方法:

@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.");
        }
    }
}

每当我调用我的save方法时,组织都会保持不变,因此各自表中的地址也是如此......但是连接表条目不是!因此,我获得了一个新的组织,一个新的地址,但它们之间没有联系。那么我在这里做错了什么?当我尝试以某种方式编辑组织时,显然也会发生这种情况。

1 个答案:

答案 0 :(得分:1)

问题在于我的服务,因为我有注释:

@Transactional(readOnly = true, propagation = Propagation.REQUIRED)

因为我通过网络流管理交易,所以他们从未提交过。所以我在persist方法中添加了@Transactional并修复了它。你也可以删除readOnly = true部分,但我没有,因为有一些我不想曝光的获取方法。