Reputation: 137
I have a Mysql table like below :
CREATE TABLE ABCD
(
TId BIGINT(8) PRIMARY KEY AUTO_INCREMENT,
TKey VARCHAR(200) NOT NULL,
TValue BIGINT(8) NOT NULL
);
it has data like below :
TId TKey TValue
1 abc 123
2 cde 345
3 def 546
What i want to do is , if i again insert entity with same TKey it'll update existing record instead of inserting new one.
Below is my code to save entity :
ABCD abcd = new ABCD();
abcd.setKey(key);
abcd.setValue(value);
abcdService.create(abcd);
Upvotes: 1
Views: 1243
Reputation: 520968
Hibernate keeps tracks of entities in your Java code using the primary key column value. So, if you create a new ABCD
entity with the key cde
and some value, Hibernate will this as a new entity, and when you save it will result in an insert into your underlying table.
If you want to instead modify the entity whose key is cde
, then you should first fetch that record:
EntityManager em = getEntityManager();
ABCD movie = em.find(ABCD.class, 2);
movie.setValue(789);
The above assumes that your framework already handles transactions for you.
Upvotes: 4