以One To Many关系更新孩子

时间:2017-06-11 08:10:48

标签: hibernate

我有两个实体Artiqule和Price

之间的OneToMany关系
@Entity(name = "ARTIQULE")
@DTOLocator(value = Artiqule.class)
public final class ArtiquleEntity extends CustomEntity{

@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
@GenericGenerator(name = "gen", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {@Parameter(name = "sequence_name", value = "GEN_ARTIQULE_ID")
        })
public Long id;

@NotNull
@Column(name = "GROUP_ID")
public Long groupId;

@NotNull
@Column(name = "METRIC_ID")
public Long metricId;

@NotNull
@Column(name = "STATUS_ID")
public Long statusId;

@NotNull
@Column(name = "OPERATOR_ID")
public Long operator;

@NotNull
@Column(name = "NAME")
public String name;

@NotNull
@Column(name = "SHORT_NAME")
public String shortName;

@ManyToOne
@JoinColumn(name = "METRIC_ID", insertable = false, updatable = false)
public MetricEntity metric;

@OneToMany(mappedBy = "artiquleEntity", fetch = FetchType.EAGER, cascade = {CascadeType.ALL})
public List<PriceEntity> prices;
}

@Entity(name = "AR_PRICE")
@DTOLocator(value = Price.class)
public class PriceEntity extends CustomEntity {

@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen")
@GenericGenerator(name = "gen", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {@org.hibernate.annotations.Parameter(name = "sequence_name", value = "GEN_AR_PRICE_ID")
        })
public Long id;

@ManyToOne
@JoinColumn(name = "AR_ID", referencedColumnName = "id")
public ArtiquleEntity artiquleEntity;

@NotNull
@Column(name = "TYPE_ID")
public Long typeId;

@NotNull
@Column(name = "PRICE")
public Long price;
}

当我插入新价格时,一切正常。但是当我尝试更新价格(子记录)时,hibernate开始插入新的价格记录(子)而不是更新现有记录,并在更新父记录之后。 我的更新

try(Session session = factory.openSession()) {
        Transaction transaction = session.beginTransaction();
        try {
            session.update(entity);
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            throw e;
        }
    }

感谢您的回复。

1 个答案:

答案 0 :(得分:0)

问题已结束。那是我的错。 错误在于DTO对象。