代码之家  ›  专栏  ›  技术社区  ›  Haem

如何使用Map<String,String>类型的元素集合更新实体?

  •  0
  • Haem  · 技术社区  · 7 年前

    public class MyEntity {
        String id;
        Map<String,String> paramsMap;
        //Many members omitted
    }
    

    相关的JPA ORM XML片段是

    <entity class="MyEntity" access="FIELD">
        <table name="myentity">
           <!--couple of unique-constraints-->
        </table>
        <attributes>
            <element-collection name="paramsMap" fetch="EAGER">
                <collection-table name="my_entity_params">
                    <join-column name="id" />
                </collection-table>
            </element-collection>
        </attributes>
    </entity>
    

    这接近于对问题的答案 this question

    我的问题是类的实体 MyEntity params -地图。发生这种情况时,Oracle DB返回一个异常,指示表的主键唯一约束 my_entity_params

    更新发生方式的近似值为:

    public void updateParam(String id, String paramName, String paramValue){
        MyEntity old=repository.findById(id)
        old.getParamsMap().put(paramName, paramValue);
        repository.save(old);
    }
    

    哪里 repository PagingAndSortingRepository .

    如果 paramsMap 在调用之前未修改 save paramsMap

    使用 one-to-many 无法工作,因为映射未指向复杂类型。同样的道理,Eclipse基金会的维基 How to map collections of Basic or Emeddable values using an ElementCollection mapping

    插入 map-key-column element-collection 似乎解决了Postgres中的问题,但在连接到Oracle数据库时问题仍然存在。

    如何让Hibernate正确更新地图内容?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Haem    7 年前

    看来我有两个类似症状的问题。

    首先,我缺少元素 map-key-column 从下面 element-collection ,因此Spring无法正确构造更新查询。通过如下更改元素可以解决此问题:

    <element-collection name="paramsMap" fetch="EAGER">
      <map-key-column name="my_entity_params_key"/>
      <collection-table name="my_entity_params">
        <join-column name="id" />
      </collection-table>
    </element-collection>
    

    第二个问题是 Oracle treats empty strings as null