0

In one application I am working on, I found that the JPA objects that are modified are not previouly loaded, I mean;

Instead of doing like this:

getEntityManager().find(Enterprise.class, idEnterprise);
//Some modifying operations

They do like this(and works!):

Enterprise obj = new Enterprise (IdEnterprise);
//Some modifying operations
getEntityManager().persist(obj);

This last solution doesnt load from database the object and it modifies the object correctly.

  1. How is this possible?
  2. Is a good practice? At least you avoid the query that loads from database, right?

Thanks

fernando1979
  • 1,727
  • 2
  • 20
  • 26

1 Answers1

0

It depends. If you are writing code from a controller class (or any application code) you shouldn't be worried about jpa stuff, so the second approach is bad and redundant.

If, instead, you are working in infrastructure code, maybe you can manually persist you entities to enable some performance optimization or simply because you want the data to persist even if the transaction fails.

I strongly suspect the second bit of code is someone creating an entity from scratch, but mixing application, domain and infrastructure code in the same method: an extremely evil practice. (Very evil, darth father evil, never do that)

gurghet
  • 7,591
  • 4
  • 36
  • 63
  • - Why the second approach is bad and redundant? - The second way you avoid one query, right? In fact, according to this thread (http://stackoverflow.com/questions/12828919/how-do-i-save-an-entity-with-foreign-key-without-loading-the-related-entity-in-j), when you want to save an entity and it has some other entities(Foreign Keys), there is no need to load them from database unless you want to modify them, then you can use "em.getReference(Account.class, accountId) " – fernando1979 Jul 07 '15 at 16:43
  • As I said, it's bad practice (because you are mixing different concerns in the same method) but you can do it if you need to optimize an established application AND you confine it to database logic. – gurghet Jul 07 '15 at 17:18