Changing positions in batch

Among the implementations of the domain models, application services, and repositories, most of them are similar to those we have covered in previous chapters. In this section, we will focus on how to change the positions of card lists and cards.

As you have seen in the APIs used to change card list and card positions, in a single request, there could be multiple position changes. We will implement the changes using the batchUpdate() method of Spring's JdbcTemplate.

Let's take a look at HibernateCardRepository, which looks like the following:

...
@Repository
public class HibernateCardRepository extends HibernateSupport<Card> implements CardRepository {
private JdbcTemplate jdbcTemplate;
HibernateCardRepository(EntityManager entityManager,
JdbcTemplate jdbcTemplate) {
super(entityManager);
this.jdbcTemplate = jdbcTemplate;
}
...
@Override
public void changePositions(final List<CardPosition> cardPositions) {
String sql = "update card set card_list_id=?,`position`=? where
id=?";

jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i)
throws SQLException {
CardPosition cardPosition = cardPositions.get(i);
ps.setLong(1, cardPosition.getCardListId().value());
ps.setInt(2, cardPosition.getPosition());
ps.setLong(3, cardPosition.getCardId().value());
}
@Override
public int getBatchSize() {
return cardPositions.size();
}
});
}
}

As you can see, besides EntityManager, we ask Spring to inject an instance of JdbcTemplate through the constructor. Inside the changePositions() method, we create an implementation of BatchPreparedStatementSetter to set the values for each SQL query, by using an instance of java.sql.PreparedStatement, and provide the size of the batch through the getBatchSize() method. In this way, we can update the positions of multiple cards in a single update SQL statement.

The implementation of changing card list positions is similar to the implementation of changing card positions. We won't list it here. Here is the commit record for implementing the board page:

Figure 12.7: Implementing the board page commit
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.129.253