Hibernate 注解 - 不区分大小写 UniqueConstraint
我有一个带有以下注释的实体:
@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"name"})})
public class Component extends Model {
...
}
是否可以使 UniqueConstraint 不区分大小写?我们正在使用 PostgreSQL。
I have an entity annotated with the following:
@Entity
@Table(uniqueConstraints={@UniqueConstraint(columnNames={"name"})})
public class Component extends Model {
...
}
Is it possible to make the UniqueConstraint case insensitive? We are using PostgreSQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议从不同的角度解决这个问题:
添加一个新列,内部列,将其命名为 lcname(代表小写名称)
更改您设置为注释的约束以使用新字段:
修改名称设置器以将 lcname 设置为客户端提供的原始名称的小写
即可。每次持久化实体时,也会保存一个小写名称。这样,如果您保存“A”,您将保存一条 lcname =“a”的记录,下次您尝试保存名称为“a”的实体时,由于 lcname 的限制,操作将失败
此更改对于从数据库中获取实体的任何人来说都是完全透明的,因为 lcname 是私有的并且没有 getter,而原始的 getName 将返回创建它的客户端最初提供的原始名称。
I would suggest attacking this problem from a different angle:
add a new column, internal one, call it lcname (stands for lower-cased name)
change the constraint you set as annotation to use the new field instead :
modify the name setter to also set lcname with a lower case of the original name provided by the client
That's it. Every time the entity will be persisted, also a lower cased name will be saved. That way if you save "A" you'll have a record with lcname = "a" saved, and next time you try to save an entity with name "a" the operation will fail due to the constraint on lcname
The change is completely transparent to anyone who fetches an entity from the database since lcname is private and there is no getter for it, while the original getName will return the original name as provided initially by the client who created it.
使用 PostgreSQL,您确实会做这样的事情来实现您的要求:
但据我所知,没有办法使用注释来实现这一点。
如果您想依靠 Hibernate 的
hbm2ddl
工具来生成架构并且仍然创建该索引,我能想到的唯一选择是利用import.sql
功能。来自 鹿特丹 JBug 和 Hibernate 的 import.sql 博客文章:With PostgreSQL, you would indeed do something like this to implement your requirement:
But there is to my knowledge no way to achieve this using annotations.
The only option I can think of if you want to rely on Hibernate's
hbm2ddl
tool to generate the schema and still have that index created would be to leverage theimport.sql
feature. From the Rotterdam JBug and Hibernate's import.sql blog post: