should i use jpa entity in rest request and/or response

Viewed 9036

I have a situation in which i can send JPA entity as rest request and/or get JPA entity as rest response

@RequestMapping(value = "/products", method = RequestMethod.POST)
public @ResponseBody ProductDetailsResponse createNewProduct(@RequestBody ProductDetails newProduct)
        throws Exception {

ProductDetails is an entity

@Entity
@Table(name = "product")
public class ProductDetails {

Should I use this, or have some kind of transformation from entities to another kind of objects

3 Answers

No don't do it. It has nothing to do with Good practice or some fancy pattern or anything.

Here are the reasons:

A JPA Entity, if we are talking Hibernate is associated with a Hibernate Session. As such Hibernate can do somethings with unintended consequences. Lets take a look:

1) Flush Mode - Flush is equivalent to a SQL update, hibernate will check for "dirty state" of an Object based on certain rules then do:

       entityManager.flush();

You may not have intended to be calling "sqlStatement.update" but lo and behold here we go

2)

`class EntityA{
     //  Defaults to Lazy Fetch
     @OneToMany
     private Set<EntityB> entityBees
 }

If we do the following from your controller and the Hibernate Session is closed you get Exceptions such as Detached entity, etc:

for (EntityB b : entityA.getEntityBees) {
    //  This is a problem
    process(b);
}

To reiterate, its not coz of some fancy GoF pattern, its coz it is dangerous. Particularly if you do not know what you are doing.

Related