Updating the JBCP calendar to use Spring Data JPA

To get familiar with Spring Data, we will first convert the JBCP calendar SQL to leverage ORM, using the Spring Data JPA starter.

Creating and maintaining SQL can be quite tedious. In the previous chapters, when we wanted to create a new CalendarUser table in the database, we had to create a fair amount of boilerplate code, as follows:

    //src/main/java/com/packtpub/springsecurity/
dataaccess/JdbcCalendarUserDao.java

public int createUser(final CalendarUser userToAdd) {
if (userToAdd == null) {
throw new IllegalArgumentException("userToAdd cannot be null");
}
if (userToAdd.getId() != null) {
throw new IllegalArgumentException("userToAdd.getId() must be
null when creating a
"+CalendarUser.class.getName());
}
KeyHoldener keyHolder = new GeratedKeyHolder();
this.jdbcOperations.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement
(Connection connection)
throws SQLException {
PreparedStatement ps = connection.prepareStatement("insert into
calendar_users (email, password, first_name, last_name)
values (?, ?, ?, ?)",
new String[] {
"id" });
ps.setString(1, userToAdd.getEmail());
ps.setString(2, userToAdd.getPassword());
ps.setString(3, userToAdd.getFirstName());
ps.setString(4, userToAdd.getLastName());
return ps;
}
}, keyHolder);
return keyHolder.getKey().intValue();
}

To create this object, we technically need 12 lines of code to perform the operation.

Now, with Spring Data JPA, the same implementation can be reduced to the following code snippet:

    //src/main/java/com/packtpub/springsecurity/dataaccess/JpaCalendarUserDao.java

public int createUser(final CalendarUser userToAdd) {
if (userToAdd == null) {
throw new IllegalArgumentException("userToAdd cannot be null");
}
if (userToAdd.getId() != null) {
throw new IllegalArgumentException("userToAdd.getId()
must be null when creating a "+CalendarUser.class.getName());
}
Set<Role> roles = new HashSet<>();
roles.add(roleRepository.findOne(0));
userToAdd.setRoles(roles);
CalendarUser result = repository.save(userToAdd);
repository.flush();
return result.getId();
}

Now, to create this object using JPA, we technically need five lines of code to perform the operation. We now need less than half the amount of code to perform the same operation.