4

I have to perform a bulk update on a table. Making a fast example :

 UPDATE Book b SET b.amount = b.amount + 1 WHERE b IN ( :books )

The problem is that b.amount can be or a NULL value or an int, and if there is a NULL value it should behave as b.amount would be equal to 1.

Is there any "cast" in JPA/JPQL or any other way to work-around this problem,

Thank you in advance,

Regards, P

redbull
  • 735
  • 3
  • 12
  • 21

3 Answers3

7

You should be able to use COALESCE:

UPDATE Book b SET b.amount = COALESCE(b.amount, 1) + 1 WHERE b IN ( :books ) 
axtavt
  • 239,438
  • 41
  • 511
  • 482
1

I would go and fix the nulls first with a separate query:

UPDATE Book set b.amount = 0 WHERE b.amount IS NULL

And also make it impossible to insert null, if it is not a legal value for your logic. For example have it @Column(nullable=false)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • In longer term this seems to be a better approach ( which I will use later ), but for now I do not have this flexibility – redbull Mar 03 '11 at 09:41
0

I used the following way to get the JDBC connection from the current JPA provider.

SessionImplementor si = (SessionImplementor) em.unwrap(Session.class);
Connection connection = si.getJdbcConnectionAccess().obtainConnection();
PreparedStatement pstmt = connection.prepareStatement("...");
// Do something
pstmt.addBatch();
pstmt.executeBatch();
si.getJdbcConnectionAccess().releaseConnection(connection);