• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Problem with refresh() method of EntityManamger in JPA

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

My simple code of saving a entity, retrieving it back using find method of entity manager in other reference and then checking both the references for equality using equals method and == operator works fine.

Now the problem is once I introduce a composite pk inside same entity.... the refresh method starts giving me problem I'm not understanding why....

Here goes my code..

I'm using @IdClass annotation on my entity class and @Id annotation on multiple properties of entity class...

the composite pk class....

package com.seed;

import java.io.*;

public class EmpPk implements Serializable
{
public EmpPk(){}

public EmpPk(int id,String first,String last){
empId=id;
firstName=first;
lastName=last;
}

int empId;
String firstName,lastName;

public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}


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

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + empId;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final EmpPk other = (EmpPk) obj;
if (empId != other.empId)
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}



}


Then entity class

package com.seed;

import javax.persistence.*;
import javax.persistence.spi.*;


@Table(name="EMPCOMPK")
@Entity
public class Employee {
public Employee(){}

private int empId;
private String firstName,lastName;
private double sal;

@Id
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}

@Id
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Id
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}


public String toString(){
return "Employee Information is \n empId is "+ empId + " FirstName is "+firstName+" lastName is "+lastName+" salary is "+sal;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + empId;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
long temp;
temp = Double.doubleToLongBits(sal);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Employee other = (Employee) obj;
if (empId != other.empId)
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (Double.doubleToLongBits(sal) != Double.doubleToLongBits(other.sal))
return false;
return true;
}

}




And the client is simple it goes like this....

package com.seed.client;
import com.seed.*;
import javax.persistence.*;
import javax.persistence.spi.*;


public class Client
{
public static void main(String[] args)
{
EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyEmployees");
EntityManager em = emf.createEntityManager();


// insert a new record in database
Employee emp = new Employee();
emp.setEmpId(120);
emp.setFirstName("Rahul");
emp.setLastName("Shah");
emp.setSal(80000.90);
EntityTransaction et=em.getTransaction();
et.begin();
em.persist(emp);
em.flush();
et.commit();

//After commit the transaction is closed
System.out.println("Checking the transaction is it active or not "+et.isActive());

//Now Find existing record
System.out.println("\n\nNow Finding the same record");
Employee emp1 = (Employee)em.find(Employee.class,new EmpPk(120,"Rahul","Shah"));
System.out.println("\n\n\n\n"+emp1);

emp1.setLastName("Barve");
System.out.println("After changing the value emp1 is \n\n"+emp1 + "\n and emp is \n\n "+emp);
System.out.println("Checking for equality of both references emp.equals(emp1) is "+emp.equals(emp1));
System.out.println("Checking for equality of both references using == operator is "+(emp==emp1));
System.out.println("Now Refreshing the data from database ");
em.refresh(emp1);
System.out.println("After Refreshing the data employee info is "+emp1);
System.out.println("Checking for equality of both references emp.equals(emp1) is "+emp.equals(emp1));
System.out.println("Checking for equality of both references using == operator is "+(emp==emp1));
/*//Remove that record
System.out.println("\n\n\t\tRemoving "+emp);
EntityTransaction et=em.getTransaction();
et.begin();
em.remove(emp);
em.flush();
et.commit();
*/
System.out.println("\n\nEntity manager is it open "+em.isOpen());
System.out.println("\n\nEntity manager Factory is it open "+emf.isOpen());
System.out.println("\n\n\t\tClosing EntityManager \n\n");

em.close();

System.out.println("\n\nEntity manager is it open "+em.isOpen());
System.out.println("\n\nEntity manager Factory is it open "+emf.isOpen());

System.out.println("\n\n\t\tClosing EntityManager Factory\n\n");
emf.close();
System.out.println("\n\nEntity manager is it open "+em.isOpen());
System.out.println("\n\nEntity manager Factory is it open "+emf.isOpen());

}
}



The orm.xml is...

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
<entity class="com.seed.Employee">
<id-class class="com.seed.EmpPk"/>
<attributes>
<id name="empId"/>
<id name="firstName"/>
<id name="lastName"/>
</attributes>
</entity>
</entity-mappings>


Persistence.xml is ok..

and the exception that I'm getting is...

C:\javaprgs\EJB3.0\JPA\04 Simple Employee with composite PK\01 @IdClass>java com
.seed.client.Client
[TopLink Info]: 2008.06.11 10:54:51.312--ServerSession(21491205)--TopLink, versi
on: Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))
[TopLink Info]: 2008.06.11 10:54:52.531--ServerSession(21491205)--file:/C:/javap
rgs/EJB3.0/JPA/04%20Simple%20Employee%20with%20composite%20PK/01%20@IdClass/-MyE
mployees login successful
Checking the transaction is it active or not false


Now Finding the same record




Employee Information is
empId is 120 FirstName is Rahul lastName is Shah salary is 80000.9
After changing the value emp1 is

Employee Information is
empId is 120 FirstName is Rahul lastName is Barve salary is 80000.9
and emp is

Employee Information is
empId is 120 FirstName is Rahul lastName is Barve salary is 80000.9
Checking for equality of both references emp.equals(emp1) is true
Checking for equality of both references using == operator is true
Now Refreshing the data from database
Exception in thread "main" javax.persistence.EntityNotFoundException: Entity no
longer exists in the database: Employee Information is
empId is 120 FirstName is Rahul lastName is Barve salary is 80000.9.
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.re
fresh(EntityManagerImpl.java:393)
at com.seed.client.Client.main(Client.java:40)



Please help me out in this.. why it's happening only in case of CompositePK...

thanks

nitin
 
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You issue is here:

>> emp1.setLastName("Barve");

You cannot change the primary key of an object.

see,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Strange_behavior.2C_unique_constraint_violation.
 
Nitin Takale
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Sutherland:
You issue is here:

>> emp1.setLastName("Barve");

You cannot change the primary key of an object.

see,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Strange_behavior.2C_unique_constraint_violation.






Great ;-) Thanks ...... a Ton...
I just forgot that.... and was trying to beat my head on the code....
It seems you are the only one who is answering this kind of queries...

Simply Great...
 
He baked a muffin that stole my car! And this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic