【问题标题】:Hibernate - automatic and generic way to check if a defined unique key constraint exists?Hibernate - 检查是否存在定义的唯一键约束的自动和通用方法?
【发布时间】:2012-06-27 00:21:10
【问题描述】:

想象一个城市到邮政编码的关系映射。 (为简单起见,不使用外键)

<class name="CityToPostalcode" table="city_to_postalcode" catalog="database">
    <id name="id" type="java.lang.Integer">
        <column name="id" />
        <generator class="identity" />
    </id>
    <property name="city" type="String">
        <column name="city" not-null="true"/>
    </property>
    <property name="postalcode" type="Integer">
        <column name="postalcode" not-null="true"/>
    </property>
    <properties name="businessKey" unique="true">
        <property name="city"/>
        <property name="postalcode"/>
    </properties>
</class>

框架中是否有一个函数来检查给定组合的唯一键“businessKey”是否唯一(也适用于单列唯一约束)?

也许结合将“businessKey”映射到一个类? (类似于composite-id的用法)

如果确实可以自动完成,为每个表编写代码以检查其业务密钥是多么的冗余。

【问题讨论】:

  • 看看@naturalid,它与@id相当

标签: hibernate unique-key


【解决方案1】:

natural Id 自动创建模式创建的唯一约束,可用于更有效地查询它。在xml中

<natural-id>
    <property name="name"/>
    <property name="org"/>
</natural-id>

naturalids 使用二级缓存效率更高,从 H4.1 开始,naturalid 加载时使用一级缓存,可以节省往返行程。除此之外,自然 id 就像普通属性一样。但是,您可以编写一个通用的自然 id 检查器

  1. 创建具有属性集的新对象
  2. 通过 sessionfactory 访问对象的类元数据
  3. 迭代自然 id 属性并使用它们从对象中获取值并在 using(propertyname, propertyvalue) 上设置它们
  4. 如果找到了复制数据,否则只保存刚刚创建的对象

【讨论】:

  • 感谢 ClassMetadata 提供的信息!
  • 在某些极少数情况下,在多次读取的事务中,通过 natural-id 保存查找确实会检索所有值为 null 的代理,并且 Hibernate.initialize() 仍然不设置值!看起来像一个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-23
  • 2021-11-11
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
相关资源
最近更新 更多