Reputation: 429
When Running below code to update only selected fields the other fields are set to null,
@Override
@Transactional
public void updateStocksPrices(Stocks stocks) {
Query query = entityManager.createNativeQuery("UPDATE stocks set price=price+(?) WHERE id=(?)", Stocks.class);
query.setParameter(1, stocks.getPrice());
query.setParameter(2, stocks.getId());
entityManager.merge(stocks);
entityManager.flush();
}
I'm using spring boot, how to update the fields that I want without setting other fields to null. Thank you
Upvotes: 1
Views: 2228
Reputation: 1265
If you are executing the update using native query, you need not merge the entity. The following code should fix this.
@Override
@Transactional
public void updateStocksPrices(Stocks stocks) {
Query query = entityManager.createNativeQuery("UPDATE stocks set price=:price WHERE id=:id");
query.setParameter("price", stocks.getPrice());
query.setParameter("id" stocks.getId());
query.executeUpdate();
}
Upvotes: 2