[英]Unique Key Constraint
What's the best practice in handling data insertion/update on a table with unique key constraints at the application level ? 在应用程序级别处理具有唯一键约束的表上的数据插入/更新的最佳实践是什么? These are what I came up with:
这些是我想出的:
Pros 优点
Cons 缺点
Pros 优点
Cons 缺点
Which one is the more widely accepted solution? 哪个是更广泛接受的解决方案? Are there alternatives to these?
有其他替代方法吗?
I'm using Java, JPA, Hibernate, and Spring BTW. 我正在使用Java,JPA,Hibernate和Spring BTW。 Any suggestions, even framework specific, are welcome!
欢迎任何建议,甚至是特定于框架的建议!
Thanks! 谢谢!
You've already pretty much sum it up. 您已经对它进行了总结。 If performance is a concern, go for 2nd way.
如果需要考虑性能,请选择第二种方法。 If integrity is a concern, go for 1st way.
如果要考虑完整性,请采用第一种方法。
I personally favor integrity over performance. 我个人更喜欢诚信而不是表现。 Hardware is pretty cheap, integrity not.
硬件很便宜,完整性不是。
A third option is to use a MERGE operation (sometimes called UPSERT) if your DBMS supports it. 第三种选择是,如果您的DBMS支持,则使用MERGE操作(有时称为UPSERT)。 There is usually a DBMS specific way of checking whether the row was inserted or not.
通常,有一种DBMS特定的方式来检查是否插入了行。
Avoid the tautology "unique" key. 避免使用重言式“唯一”键。 Keys ARE unique, so the word "key" is quite sufficient to say what you mean.
键是唯一的,因此“键”一词足以说明您的意思。
I like the "optimistic" approach ("do nothing"). 我喜欢“乐观”的方法(“什么都不做”)。 You already enumerated the pros.
您已经列举了优点。 You are right that in this case you delegate validation to the DB layer.
没错,在这种情况下,您将验证委派给数据库层。 But inf you are using JPA the DB layer is also generated by java layer, so actually your validation depends on your annotation in java code.
但是,如果您使用的是JPA,则DB层也是由Java层生成的,因此实际上您的验证取决于Java代码中的注释。 Therefore it is not a big crime.
因此,这不是大罪。
A unique key is usually a business requirement, so you should use the business layer to check whether the one you intend to use is available. 唯一密钥通常是一项业务需求,因此您应使用业务层来检查您打算使用的密钥是否可用。 Delegating the checking to the database is an optimization, that should only be done when needed.
将检查委托给数据库是一种优化,只能在需要时执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.