1

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);
2
  • 1
    This should be the default behavior for a Hibernate entity, I think. What is wrong with your current Java code? Commented Jun 12, 2019 at 5:21
  • If i Set key -> cde and Value - > 789 , It'll insert new record. TId TKey TValue 4 cde 789. What i want to do is it should update TId -> 2 with 789. Commented Jun 12, 2019 at 5:34

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to find entity by Tkey like : ABCD movie = em.find(ABCD.class, 'cde'); Because i have on TKey Param and i want to find entity with non primary key. is it possible?
You should usd either a JPA/HQL query for this, or a raw SQL query. If you want to sift through all entities, you will need some sort of loop, and this is not the best way to do this. The best way to do this is to let the database do the heavy lifting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.