java developer java developer - 2 months ago 16
Java Question

difference between entitymanager merge and execute update

What is the difference between

entitymanager.merge
and
query.executeUpdate
.

I have one entity order

@Entity
@Table(name="ORDERS",schema ="AMZ")
public class Orders {

@Id
@SequenceGenerator(name = "pk_sequence", sequenceName = "ORDERS_SEQ", schema = "AMZ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence")
@Column(name = "ORDERS_ID")
private long id;

@Column(name = "STATUS")
private Status status;


I have my DAO class

@Repository
@Transactional
public class InvoiceDAO {

@PersistenceContext
private EntityManager entityManager;

public void update(Order order){
updateInvoice();
mergeInvoice(Order order);
}

public void updateInvoice(){
entitymanager.createQuery("update Orders set status = 'ERROR' where id=12").executeUpdate();
}

public void mergeInvoice(Order order){
entitymanager.merge(order);
}


}


In the above, merge happens before
executeUpdate();
even though there are several transactions in between execute update is the last transaction which occurs. WHY?

I tried
entityManager.flush();
but it didn't work.

Answer

I resolved this by calling the update and merge methods from service layer. I found that for the transaction to get commit I have to return out of my DAO.

public void update(Order order){
orderDao.updateInvoice();
orderDao.mergeInvoice(Order order);
}