In database level we can have an insert statement with exist query embedded.
example,
INSERT INTO MyTable (ID,Col1,Col2,...)
SELECT @IDValue,@Col1Value,@Col2Value, ...
WHERE NOT EXISTS (SELECT ID
FROM MyTable
WHERE ID=@IDValue)
SELECT * FROM MyTable Where ID=@IDValue
Is there any way we can achieve this via Hibernate? Does Hibernate has any logic like DB insert only if exist to avoid duplicate insert?
We don't want to introduce versioning and look for a solution which does the above.
Thanks.
Solved
I don't actually know if Hibernate per se has support for this, but what you want can, and probably should, be enforced at the database level. Just create a unique index/constraint on the ID column. The exact syntax would vary from database to database, but in MySQL could try:
ALTER TABLE MyTable ADD UNIQUE (ID);
Then inserts with a duplicate key would fail at the database level, and your Java code should be ready, possibly by catching an exception.
To preserve uniqueness and to avoid constraint exceptions you can do a check at DAO level, like this:
class MyTableDao extends SomeAbstractDao {
Integer save(MyTable myTable) {
Integer id = findBySomeFields(myTable);
return id != null ? id : save(myTable);
}
}
Actually you can use SQLInsert annotation :
@Entity
@Table(name="story_count")
@SQLInsert( sql="INSERT INTO story_count(id, view_count) VALUES (?, ?)
ON DUPLICATE KEY UPDATE set view_count = view_count + 1")
public class StoryCount
DUPLICATE KEY is for MySQL, you can modify this to use a merge
EDIT : Actually you can use a procedure in the SQLInsert, so you'll need to make one for each database
@SQLInsert(sql="call PROC_ADD_USER(:P_ID,:P_COL1,:P_COL2,:P_COL3, ...)", callable=true)
But i know, it's still lacking some beauty
Comments
Post a Comment