Question

I can't seem to find a straight answer for this anywhere, I am trying to update an existing database entry using a java class. The user enters their details in a form on a jsp page, which then calls the servlet and assigns these values to a user object. This object is then passed to an edit profile method to conduct the database operation.

When I try to merge it the object it creates a new entry, when I create the update query and pass that it doesn't update. Could someone please give me an example of how to conduct the update using java.

The Java:

public static void editUserProfile(User editUser) {

    try{
         factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
         EntityManager em = factory.createEntityManager();
        System.out.println("In edit profile Method");

        int ID = editUser.get_Id();
        String name = editUser.getName();
        String address1 = editUser.getAddress1();
        String address2 = editUser.getAddress2();
        String county = editUser.getCounty();
        String phone = editUser.getTelephone();
        String email = editUser.getEmail();
        String website = editUser.getWebsite();
        String information = editUser.getInformation();
        String password = editUser.getPassword();
        String searchQuery = "UPDATE User SET name='"+name+"' address1='"+address1+"' address2='"+address2+"' "
                           + "county='"+county+"' phone='"+phone+"' email='"+email+"' website='"+website+"' "
                           + "information='"+information+"' password='"+password+"' WHERE id='"+ID+"'";

         // Update user in the database
         em.getTransaction().begin();
         //Query r = em.createNativeQuery(searchQuery);
         em.merge(searchQuery);

         em.getTransaction().commit();

         em.close();
Was it helpful?

Solution

It seems like you are confusing JPA with straight JDBC.

A good overview of JPA is here (see the putting it all together portion)

https://glassfish.java.net/javaee5/persistence/persistence-example.html

You are calling em.merge() with a String, when you should really be updating the object and then telling the entity manager to merge the changes (which saves them to the database).

The UPDATE statement you've crafted is sort of how you'd do it with JDBC, but you'd use a Connection/PreparedStatement with ? for parameters/etc... It seems though like your sample code is JPA based.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top