Search code examples
springjakarta-eeopenjpaopenjpa-maven-plugin

OPEN JPA find() could not retrieve the value of the entity from my Database


There is a weird scenario that I had encountered in my User log in program.

  1. Insert the record.. Userid password etc.
  2. Insert the record using merge();
  3. Then close the IDE (Netbeans)
  4. Open IDE Netbeans then start servers, start database connection.
  5. Open the log in browser.
  6. log in using the inserted record.
  7. My program could not detect the record on the table.

When debugging, after the find() it would not populate my entity.. Maybe there is still another step to populate the entity?

LoginAction

package lotmovement.action;

import com.opensymphony.xwork2.ActionSupport;
import lotmovement.business.crud.RecordExistUserProfile;
import org.apache.commons.lang3.StringUtils;


public class LoginAction extends ActionSupport{

    private String userName;
    private RecordExistUserProfile recordExistUserProfile;


    private String password;

    @Override
    public void validate(){

        if(StringUtils.isEmpty(getUserName())){
            addFieldError("userName","Username must not be blanks.");

                }

        else{

            if(!recordExistUserProfile.checkrecordexist(getUserName())){
                addFieldError("userName","Username don't exist.");
            }



        }        



        if(StringUtils.isEmpty(getPassword())){
            addFieldError("password","Password must not be blanks.");
        }
        else{

         if(!recordExistUserProfile.CheckPasswordCorrect(getUserName(), getPassword())){
                addFieldError("userName","Password not correct");
            }


        }



    }


    public String execute(){

       return SUCCESS;
    }


    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

      public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }   



     public RecordExistUserProfile getRecordExistUserProfile() {
        return recordExistUserProfile;
    }

    public void setRecordExistUserProfile(RecordExistUserProfile recordExistUserProfile) {
        this.recordExistUserProfile = recordExistUserProfile;
    }




}

Validator Program

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package lotmovement.business.crud;

import lotmovement.business.entity.UserProfile;

/** * * @author god-gavedmework */ public class RecordExistUserProfile {

private EntityStart entityStart;
private UserProfile userProfile;


public boolean checkrecordexist(String userId) {
    entityStart.StartDbaseConnection();
    entityStart.em.find(UserProfile.class, userId);

    if (userId.equals(userProfile.getUserId())) {
        return true;
    } else {
        return false;
    }
}

public boolean CheckPasswordCorrect(String userId, String password) {
    entityStart.StartDbaseConnection();

    entityStart.em.find(UserProfile.class, userId);

    if (password.equals(userProfile.getPassword())) {
        return true;
    } else {
        return false; ---> It will step here.
    }

}



public UserProfile getUserProfile() {
    return userProfile;
}

public void setUserProfile(UserProfile userProfile) {
    this.userProfile = userProfile;
}

public EntityStart getEntityStart() {
    return entityStart;
}

public void setEntityStart(EntityStart entityStart) {
    this.entityStart = entityStart;
}

}

Entity

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lotmovement.business.entity;
import java.io.Serializable;
import javax.persistence.*;


/**
 *
 * @author god-gavedmework
 */

@Entity(name = "USERPROFILE") //Name of the entity
public class UserProfile implements Serializable{

    @Id //signifies the primary key
    @Column(name = "USER_ID", nullable = false,length = 20)


    private String userId;


    @Column(name = "PASSWORD", nullable = false,length = 20)
    private String password;

    @Column(name = "FIRST_NAME", nullable = false,length = 20)

    private String firstName;
    @Column(name = "LAST_NAME", nullable = false,length = 50)

    private String lastName;

    @Column(name = "SECURITY_LEVEL", nullable = false,length = 4)
    private int securityLevel; 


    @Version
    @Column(name = "LAST_UPDATED_TIME")
    private java.sql.Timestamp updatedTime;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getSecurityLevel() {
        return securityLevel;
    }

    public void setSecurityLevel(int securityLevel) {
        this.securityLevel = securityLevel;
    }

    public java.sql.Timestamp getUpdatedTime() {
        return updatedTime;
    }

    public void setUpdatedTime(java.sql.Timestamp updatedTime) {
        this.updatedTime = updatedTime;
    }

}


*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lotmovement.business.crud;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import lotmovement.business.entity.UserProfile;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;

public class EntityStart {
     EntityManagerFactory factory;
     EntityManager em;



    public void StartDbaseConnection()
    {

        factory = Persistence.createEntityManagerFactory("LotMovementPU");
        em = factory.createEntityManager();

    }

    public void StartPopulateTransaction(Object entity){

        EntityTransaction userTransaction = em.getTransaction();

        userTransaction.begin();

        em.merge(entity);
        userTransaction.commit();

        em.close();

    }

    public void CloseDbaseConnection(){
        factory.close();
    }

}

Using Trace as adviced, This is the log of the SQL

SELECT t0.LAST_UPDATED_TIME, t0.FIRST_NAME, t0.LAST_NAME, t0.PASSWORD, t0.SECURITY_LEVEL FROM USERPROFILE t0 WHERE t0.USER_ID = ? [params=(String) tok]

This is the record:

USER_ID FIRST_NAME  LAST_NAME   PASSWORD    SECURITY_LEVEL  LAST_UPDATED_TIME
tok           1      1          1           1                  2012-12-13 08:46:48.802                        

Added Persistence.XML

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="LotMovementPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <non-jta-data-source/>
    <class>lotmovement.business.entity.UserProfile</class>
    <properties>
      <property name="openjpa.ConnectionURL" value="jdbc:derby://localhost:1527/LotMovementDBase"/>
      <property name="openjpa.ConnectionDriverName" value="org.apache.derby.jdbc.ClientDriver"/>
      <property name="openjpa.ConnectionUserName" value="toksis"/>
      <property name="openjpa.ConnectionPassword" value="bitoytoksis"/>
      <property name="openjpa.Log" value="SQL=TRACE"/>
      <property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
    </properties>
  </persistence-unit>
</persistence>

I discovered the root cause of the problem. It is on how I instantiate the class in Spring Plugin.

When I change the find() statement to below, it will now work.

  UserProfile up = entityStart.em.find(UserProfile.class, "tok"); 

But how can i initialize this one using Spring? codes below dont work?

private UserProfile userProfile;

...... some codes here.

entityStart.em.find(UserProfile.class, userId);


  ..... getter setter

Solution

  • The Root cause of the problem.

    entityStart.em.find(UserProfile.class, userId); --> it should be

    userProfile = entityStart.em.find(UserProfile.class, userId);