Sping JPA @OneToOne双向空字段

时间:2018-08-17 06:45:35

标签: java spring hibernate spring-data-jpa

我有两个类,名称之一是Customer,此客户具有CustomerAccount类实例。像这样;

@Entity
@Table(name="tbl_customer") 
public class Customer extends BaseModel {

    private static final long serialVersionUID = 6330478175909499801L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator="customer_s")
    @SequenceGenerator(name="customer_s", sequenceName="customer_s", allocationSize=1)
    @Column(name="id")
    private Integer id;

    @JoinColumn(name = "customer_account_id")
    @OneToOne(mappedBy = "customer", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    private CustomerAccount customerAccount;

    public CustomerAccount getCustomerAccount() {
        return customerAccount;
    }

    public void setCustomerAccount(final CustomerAccount customerAccount) {
        if (customerAccount == null) {
            if (this.customerAccount !=null) {
                this.customerAccount.Customer(null);
            }
        } else {
            customerAccount.setCustomer(this);
        }
        this.customerAccount = customerAccount;
    }

    //..    
}

@Entity
@Table(name="tbl_customer_account")
public class CustomerAccount extends BaseModel {

    private static final long serialVersionUID = 3995542305560456290L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "customer_account_s")
    @SequenceGenerator(name = "customer_account_s", sequenceName = "customer_account_s", allocationSize = 1)
    @Column(name="id")
    private Integer id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Customer customer;

    //..

}

这是我的CustomerServiceImpl,

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao; 

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private void saveOrUpdate(final CustomerResult result) throws Exception {
        CustomerMapper.getInstance().dtoToDomain(result.getDtoEntity(), result.getDomainEntity()); 
        setCustomerData(result);
        customerDao.save(result.getDomainEntity()); 
        result.updateDtoIdAndVersion();
    }

    private void setCustomerData(final CustomerResult result) throws Exception{
        final CustomerAccount customerAccount = new CustomerAccount();
        customerAccount.setCustomer(result.getDomainEntity());  
        result.getDomainEntity().setCustomerAccount(customerAccount);
    }

}

我的问题是当我保留客户时,Customer和CustomerAccount保留到数据库中。但在客户实体中,“ customerAccount”字段为空。我也提到了这篇文章bidirectional entity associations

0 个答案:

没有答案