Good day. It is necessary to insert the data immediately in 2 tables. As far as I understand this should be done in the transaction block. Tell me how to do it correctly in the jsbcTemplate. DB - postgre. My dao methods still look like this:

@Override public int createUser(User user) { return jdbcTemplate.update(SQL_CREATE_USER, user.getFirstName(), user.getLastName(),true,user.getRegistrationDate(), user.getPassword(), user.getEmail()); } @Override public int addRole(User user, Role role) { return jdbcTemplate.update(SQL_ADD_ROLE, user.getId(), role.getId()); } 

Service add a full user (with roles) in the database

 @Override public void createUser(User user) { userDAO.createUser(user); for (Role role : user.getRoles()) { userDAO.addRole(userDAO.getByEmail(user.getEmail()), role); } 

I was thinking of somehow inserting the left connection with autoComit = false into daoski, and working with it, but judging by the documentation, springJdbc in this case does something differently .. Tell me how it is correct. Thank.

    1 answer 1

    In Spring, transaction management is moved to a separate spring-tx module.

    Commonly used are declarative transactions that are declared at the service level. In this case, you need to connect the transaction manager and mark the method or the entire class of your service with the @Transactional annotation, the rest will be @Transactional Spring itself.

    Software transaction management is also possible, but it is made somewhat more complicated .

    In fact, the network has a ton of guides on this issue to write another one. You can, for example, pay attention to this .

    • Thank you very much. Everything worked out! - Aleksei