Grails GORM 对 BigDecimal 列表的唯一约束
我有一个类:
class Test {
List<BigDecimal> values
static constraints = {
values(unique: true)
}
}
但是,
void testUniqueness() {
List valList = [
new BigDecimal(1),
new BigDecimal(1)
]
def testInstance = new Test(values: valList)
mockForConstraintsTests(Test, [testInstance])
assertFalse "Validation should fail for non-unique values", testInstance.validate()
}
这个断言失败了,因为 .validate() 是 true!
我想要一个 BigDecimal 的列表,它对于测试对象的每个实例都是唯一的
I've got a class:
class Test {
List<BigDecimal> values
static constraints = {
values(unique: true)
}
}
However,
void testUniqueness() {
List valList = [
new BigDecimal(1),
new BigDecimal(1)
]
def testInstance = new Test(values: valList)
mockForConstraintsTests(Test, [testInstance])
assertFalse "Validation should fail for non-unique values", testInstance.validate()
}
This assert fails, because .validate() is true!
I want a list of BigDecimal's which is unique to each instance of the Test object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事情不是这样的。如果您考虑更简单的事情,例如“字符串用户名”,则唯一性检查会在数据库中该列上创建唯一索引。因此两个用户不能具有相同的用户名/登录名/等。
但您要求列表的内容是唯一的。约束(如果有意义)将比较两个列表并确保没有两个
Test
实例的values
列表相同。例如[1,3,5]<-> [1, 3] 可以,但是 [1, 3, 5] <-> [1,3,5]将会失败。这实施起来不切实际并且不受支持。这相当于要求用户名不重复字母 - “burt”可以,但“burtbeckwith”会失败。如果您想在集合中拥有唯一的元素,只需将其从列表更改为集合即可。你甚至不需要约束:
This is not how it works. If you think about something simpler, e.g. "String username", the uniqueness check creates a unique index in the database on that column. So two users cannot have the same username/login/etc.
But you're asking for the contents of a List to be unique. The constraint (if it made sense) would compare two Lists and ensure that no two
Test
instances'values
lists are the same. For example [1, 3, 5] <-> [1, 3] would be ok, but [1, 3, 5] <-> [1, 3, 5] would fail. This would be impractical to implement and is not supported. It's the equivalent of requiring that a username not repeat a letter - "burt" would be ok but "burtbeckwith" would fail.If you want to have unique elements in a collection, just change it from a List to a Set. You don't even need a constraint: