JPA潜在的同步问题

时间:2015-09-18 13:12:39

标签: jpa spring-data-jpa

在我的房客类中,我有

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "lodger", orphanRemoval=true)
//  @JsonBackReference
private List<RoomPayment> roomPaymentList;

在我的RoomPayment课程中我有

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "lodger_id")
private Lodger lodger;

其实我做了

@Override
public Long save(RoomPaymentDto roomPaymentDto) {

    RoomPayment roomPayment;

    if (roomPaymentDto.getRoomPaymentId() != null) {
        roomPayment = repository.findOne(roomPaymentDto.getRoomPaymentId());
    } else {
        roomPayment = new RoomPayment();
    }

    MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
    mapperFactory.classMap(RoomPayment.class, RoomPaymentDto.class).byDefault().register();

    MapperFacade mapper = mapperFactory.getMapperFacade();

    mapper.map(roomPaymentDto, roomPayment);

    repository.save(roomPayment);

    return roomPayment.getRoomPayementId();
}

在这种方法中,我是否需要获取Lodger并将其分配给roomPayment?

1 个答案:

答案 0 :(得分:0)

不,如果dto当然包含正确的Lodger

重点是从RoomPayment到关联的Lodger没有级联,这意味着当您保存roomPayment时,Hibernate不会抱怨分离的对象。

Hibernate将从lodger实例中获取用于维护关联的id(因为RoomPayment是关联的所有者)。