Arasu
Arasu

Reputation: 2148

Update a table using JPA in Play Framework

I'm trying to update a table using JPA

EntityManager em=JPA.em();
EntityTransaction entr = em.getTransaction();
try{
if(!entr.isActive())
  entr.begin();
  Tblrecordtypefields updateTblrecordtypes = em.find(Tblrecordtypefields.class,9);
  updateTblrecordtypes.setFieldlabel("JPATest");
  em.getTransaction().commit();
}finally
{
if(entr.isActive())
entr.rollback();
}

i'm getting the error NullPointerException occured : null at updateTblrecordtypes.setFieldlabel("JPATest"); What should i do.

Upvotes: 2

Views: 1843

Answers (3)

Arasu
Arasu

Reputation: 2148

I have changed my code as below

Tblrecordtypefields updateTblrecordtypeFields = Tblrecordtypefields.findById(9);
updateTblrecordtypeFields.setFieldlabel("Test");
validation.valid(updateTblrecordtypeFields);
if(validation.hasErrors()) 
{
    updateTblrecordtypeFields.refresh();
}
else
{
    updateTblrecordtypeFields.save();
}

in my model class

public void setFieldlabel(String fieldlabel) {
this.fieldlabel = fieldlabel;
}

Works Fine.....

Upvotes: 0

Pere Villega
Pere Villega

Reputation: 16439

I see some possible issues in there:

First, Play manages the transactions on it's own. A transaction is created at the beginning of the request and committed (rollback if exception) at the end. You are trying to force your way into it, that's not recommended. To manage the entity, just do an entity.save() to mark it as "to be saved" and don't do tht to ignore any changes.

Second, if you are using the Model class in Play (as you should) you can use the "find" and "findById" methods provided by this class. This is recommened, instead of using the EntityManager directly.

See the documentation for more information.

Basically, redo your code to follow the Play way, to avoid problems :)

EDIT: as a clarification, I'm not really answering your question on why you get the NPE, but I think that as you are forcing your way into the settings of the framework you might (maybe not!) be seeing unexpected artifacts that will dissapear once you fix your code to follow convention.

If after that you still have the error let us know :)

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691913

This means that there is no row with ID 9 in the database table mapped by the entity Tblrecordtypefields.

BTW: I find it very questionable to commit a transaction in a method which is not necessary the one that started the transaction.

Upvotes: 1

Related Questions