2

I have a Spring CrudRepository that I am using to persist an Entity. However, my Entity has some transient fields that I do not want stored in the database, however, I don't want to lose them when I call save() but it appears I always get a brand new, different object back from the save() method. And thus I lose my transient values.

If I don't use the object that is returned and just keep using my original object that I called save() on, I can only call save() on it once, otherwise it complains the Entity was updated by another session.

Any idea how to either get save() to return me my same object back? Should I be using a different repository? Can I add some sort of annotations to change the behavior?

@Override
@Transactional
public TestRun saveTestRun(TestRun run) 
{
    logger.debug("Saving TestRun with Id: " + run.getId() + " " + run.toString());
    logger.debug("Timeout 1: " + run.getTimeout());
    run.setTimeout(10000000);  // set transient field

    logger.debug("Timeout 2: " + run.getTimeout());
    TestRun r2 = this.repository.save(run);

    logger.debug("Timeout 3: " + r2.getTimeout());

    logger.debug("Saved TestRun with Id: " + r2.getId() + " " + r2.toString() );

    return r2;
}

And this produces:

Saving TestRun with Id: 2 TestRun@4c4d810e
Timeout 1: 90
Timeout 2: 10000000
Payload no-arg constructor
TestRun constructor
TestRun no-arg constructor
Timeout 3: 90
Saved TestRun with Id: 2 TestRun@25a14d5c
David Hergert
  • 1,442
  • 3
  • 14
  • 22

2 Answers2

0

If I don't use the object that is returned and just keep using my original object that I called save() on, I can only call save() on it once, otherwise it complains the Entity was updated by another session.

You can use saveOrUpdate(Object object) method (of Hibernate session), if you wanted to use same entity object over multiple sessions OR the other option is to use persist() (return type void), but with persist() (generated id will not be returned), you can look here

You can look here for session API.

Community
  • 1
  • 1
Vasu
  • 21,832
  • 11
  • 51
  • 67
  • Ok - so I am using org.springframework.data.repository.CrudRepository for my interactions with Hibernate. So I am clear, that does not have a persist method so I would need to get a handle on the Hibernate Session directly and perform the save and/or persist methods? Just trying to use the out of the box framework provided by Spring as much as possible if I can, but if I need to talk to the Hibernate session I can. – David Hergert Nov 16 '16 at 16:30
0

Any idea how to either get save() to return me my same object back?

save(object) will return the generated identifier only and NOT the object you have passed to it. so get that identifier returned by the save method, then set it to the object manually if you need that id.

amFroz
  • 95
  • 1
  • 12