Solved

update query

Posted on 2010-09-16
17
311 Views
Last Modified: 2012-06-27
I have an entity class by the name of User and table name is user_info. I am using hibernate to presist the data. An object is passed as a parameter to one of my service method. I execute a query to see if the pinNumber exist for that user in the table. if it is then do an update else do an insert.

Insert works fine but when doing an update hibernate throws an exception that it cannot update because the pin already exist. below is my Entity User class. The Pin has a unique identifier in the table also. I think one of the reason might be because i have annotation @Id on pinNumber but if i remove it i get an exception when deploying my code that identifier needs to be defined in the entity.


@Entity

@Table(name="user_info")

public class User {



private Integer pinNumber;



private String firstName;



.

.

.



public void setPinNumber(Integer pinNumber) {

this.setPinNumber = pinNumber;

}



@Id

@Column(name="pin_number")

public Integer getPinNumber() {

return pinNumber;

}

Open in new window

0
Comment
Question by:Micheal_Male
  • 10
  • 7
17 Comments
 
LVL 92

Expert Comment

by:objects
ID: 33698034
what properties are you updating?

can you post your update code
0
 

Author Comment

by:Micheal_Male
ID: 33698075
Below is the code.
public void saveUpdate(final User user) {

Session sess = null;

   try {

      SessionFactory fact = new Configuration()

.configure().buildSessionFactory();

      sess = fact.openSession();

      Transaction tr = sess.beginTransaction();

      sess.update(user);

      tr.commit();

      sess.close();

      System.out.println("Update successfully!");

    }

    catch(Exception e){

      System.out.println(e.getMessage());

    }

}

Open in new window

0
 
LVL 92

Expert Comment

by:objects
ID: 33698096
where is that user being loaded and updated?
0
 

Author Comment

by:Micheal_Male
ID: 33698130
The user is loaded in the main method.

User user = new User();
user.setFirstName("dummy");
user.setLastName("test");
user.setPinNumber("112");

call the UserService and execute the above update statement.
userService.saveUpdate(user);

I am testing the update senario since the insert senario works with no problem.
0
 

Author Comment

by:Micheal_Male
ID: 33698170
Or is it possible to write a namedQuery which contains an update statement and will update all the attributes for the User based on the pinNumber provided not just one column ?.

@NamedQueries({
@NamedQuery(name="updateUserRecord", query="UPDATE User s SET s.firstName= ? WHERE s.pinNumber= :pinNumber")
})

I would like to do to update the Whole User Object by just passing the pin.
0
 
LVL 92

Accepted Solution

by:
objects earned 250 total points
ID: 33698173
thats a new user, to update an existing user you need to load it from the database
0
 

Author Comment

by:Micheal_Male
ID: 33698207
objects. what difference does it make if i load the user by executing a select statement for getting the values or executing an update statement ?. If i load the user and then execute an update i don't see how it will update then and not the way i am doing. Since the User object already contains all the values then what's the point of getting the old values and then executing the update statement ? May be i am not getting the hibernate update correctly. Could you ellaborate a little bit if you don't mind ?
0
 
LVL 92

Expert Comment

by:objects
ID: 33698256
the update() method takes an object and makes it persistent (it has nothing to do with a sql update), so in your case it tries to make the specified object persistent and fails because it already exists in the database.
In normal hibernate usage you shouldn't need to call it all.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 92

Expert Comment

by:objects
ID: 33698261
0
 

Author Comment

by:Micheal_Male
ID: 33698331
I did loaded a new User Object which contains all the values from the database based on the pin and then i used the update statement and passed the User object whose values were loaded by executing the select statement on user_info and also got the same error :-

A different object with the same identifier was already associated with the session User#112.

i read the docs a little bit and i saw that if it's in a presistent state then a unique identifier is assigned to your Object. However, my question is which method should i use to update the User ?.
0
 

Author Comment

by:Micheal_Male
ID: 33698470
I did this and the exception is gone .

User us = userDao.getUserInfoByPin(user.getPinNumber).get(0);
sess.update(us);

It did not throw an exception but the record was never updated.
0
 
LVL 92

Expert Comment

by:objects
ID: 33698560
You are misunderstanding what update method is for
0
 
LVL 92

Expert Comment

by:objects
ID: 33698568
Hibernate will handle updating the database for transparently
The update method has an entirely different purpose
0
 

Author Comment

by:Micheal_Male
ID: 33698593
Yea i am reading the docs. Disregard my previous post as it will always work because i was passing the same values for the User Object what was retrieved from the database :). It looks like the update method does not needs to be called. Instead of update you can use the merge method which will fix my issue. However, when i try to do this :-

sess.merge(user);

I get could not synchronize database state with session. Failed to execute the batch update. Coming close now.
0
 

Author Comment

by:Micheal_Male
ID: 33698639
Also, i know i can use the setter methods once i get the identify of the Object in session but there are so many attributes that it will take me 30 min to set all the new values to the existing object and then use merge. That is why i am trying to see if i ca copy the new values to the existing object and then use merge. May be that might fix my issue.
0
 

Author Comment

by:Micheal_Male
ID: 33698647
Thanks objects. I was able to make it work. retrieved the object from the current session and then map it to your new values and then use the merge method to update the existing state of that object. I might bug you later on also for more questions. Hibernate is very powerful but at the same time very very complex.
0
 

Author Closing Comment

by:Micheal_Male
ID: 33698653
Works great now.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now