Solved

update query

Posted on 2010-09-16
17
320 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

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
 
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

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Suggested Courses

630 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