jpa合并不起作用

时间:2010-07-09 09:23:38

标签: java orm jpa merge

我在使用JPA合并对象时遇到问题。我的代码是这样的。

EntityTransaction entr = em.getTransaction();

entr.begin();

Query q = em
  .createQuery("SELECT filterName FROM IbFilterName filterName where"
    + " filterName.filterId = 42352 ");

List<IbFilterName> filterNameList = q.getResultList();

for(IbFilterName filterName : filterNameList){
   String values = filterName.getFilterValues();
   filterName.setFilterValues(values+"Saranya");
   em.merge(filterName);
}

entr.commit();

我的实体是

 @Id
 @SequenceGenerator(name = "IB_FILTER_NAMES_FILTERID_GENERATOR", sequenceName = "IB_LOGIN_HISTORY_SEQ")
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IB_FILTER_NAMES_FILTERID_GENERATOR")
 @Column(name = "FILTER_ID")
 protected long filterId;

 @Column(name = "EXTERNAL_USER")
 protected String externalUser;

 @Column(name = "FILTER_NAME")
 protected String filterName;

 @Column(name = "FILTER_VALUES")
 protected String filterValues;

 // bi-directional many-to-one association to IbPortfolioFilterMapping
 @OneToMany(mappedBy = "ibFilterName")
 private Set<IbPortfolioFilterMapping> ibPortfolioFilterMappings;

当我运行我的测试用例时,merge不会更新我的filtername对象,JPA也不会在控制台中触发任何查询。

任何人都可以建议我做错了什么?

1 个答案:

答案 0 :(得分:2)

您确定第一个查询实际上是在检索记录吗? IMO,此查询期望long作为参数。

此外,由于您的实体未分离,我建议 NOT 调用merge并让JPA自动检测并刷新更改:

em.getTransaction().begin();

Query q = em
  .createQuery("SELECT filterName FROM IbFilterName filterName WHERE"
    + " filterName.filterId = :id ").setParameter("id", 42352L);

List<IbFilterName> filterNameList = q.getResultList();

for(IbFilterName filterName : filterNameList){
    String values = filterName.getFilterValues();
    filterName.setFilterValues(values + "Saranya");
    //em.merge(filterName); // DON'T
}

em.getTransaction().commit();