用列表更新Hibernate

时间:2016-06-27 14:25:02

标签: java hibernate

我想在更新语句中更新ManyToMany关系。 我正在使用Reference类,这里是类:

public class Reference implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="user_gen")
@SequenceGenerator(name="user_gen", sequenceName="SEQ_USER")
@Column(name = "DOCUMENTID", nullable = false)
private int documentID;

@Column(name = "REFERENCE")
private String reference = "";

@Column(name = "CODE")
private String code = "";

@Column(name = "REMARK")
private String remark = "";

@Column(name = "TITLE")
private String title = "";

@ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(name = "DOCUMENTS_MACHINES", joinColumns = { @JoinColumn(name = "DOCUMENTID") }, inverseJoinColumns = { @JoinColumn(name = "MACHINEID") })
private Set<Machine> machines = new HashSet<Machine>();

我想知道是否可以更新HQL语句中的ManyToMany关系,因为session.update(object)会因缺少属性而导致冲突问题。

我尝试了什么:

     String hqlUpdate = "update Reference r " + 
            "set r.title = :title, " +
            "r.machines = :machines " +
            "where r.documentID = :id";

    int updatedEntities = session.createQuery( hqlUpdate )
            .setString("title", reference.getTitle())
            .setParameterList("machines", reference.getMachines())
            .setInteger("id", reference.getDocumentID())
            .executeUpdate();

但是,它不起作用,所以我的问题是:是否可以更新集合以及如何更新? 感谢

1 个答案:

答案 0 :(得分:0)

检查多对多hibernate更新映射查询示例:

many to many hibernate update

另请参阅CascadeType。您可以使用关系注释中的 CascadeType 直接设置保存/更新操作的行为。