Spring / Hibernate - objects that are implicitly persisted

In the following code, the CustomerService.test () method implicitly stores the customer object, i.e. without calling the merge () or update () method. Why is this and how can I get it to persist objects only when I explicitly call the merge / update?

Controller:

@Controller
@RequestMapping("/samples")
public class Samples {
    @Autowired
    private CustomerService customerService;


    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public String test(){
        customerService.test();
        return "ok";
    }
}

      

Service:

@Service
@Transactional
public class CustomerService {

    @Autowired
    private BaseDao baseDao;

    public Customer findById(Long id) {
        return baseDao.find(Customer.class,id);
    }

    public void test() {
        Customer customer = findById(1L);
        customer.setEmail("a@b.com");
    }
}

      

Tao:

@Repository("baseDao")
public class BaseDao {
    @PersistenceContext
    private EntityManager em;

    public void create(BaseEntity entity) {
        em.persist(entity);
    }

    public <T> List<T> list(Class<T> entityClass) {
        Session session = (Session) em.getDelegate();
        List<T> list = session.createCriteria(entityClass).list();
        return list;
    }

    public <T> T find(Class<T> entityClass, long primaryKey) {
        return em.find(entityClass, primaryKey);
    }

    public <T> T update(T entity) {
        return em.merge(entity);
    }

    public void remove(BaseEntity entity) {
        em.remove(entity);

    }

    public void remove(Class<? extends BaseEntity> entityClass, long primaryKey) {
        BaseEntity entity = em.find(entityClass, primaryKey);
        if (entity != null) {
            em.remove(entity);
        }
    }
}

      

+3


source to share


1 answer


You need to know that the method test

is in a Hibernate transaction. Therefore, you need to know the life cycle of your organization.

Hibernation life cycle



After loading your object, its state is Permanent . When you commit a transaction, Hibernate checks all persistent objects in the transaction: if they are dirty (have changes), they are updated.

Pulling up this diagram, you can evict()

create your entity or change its email after the transaction.

+3


source







All Articles