Spring Boot+JPA+Mysql--事务操作

 

数据访问层

Spring Boot+JPA+Mysql--事务操作_第1张图片

public interface BookRepository extends JpaRepository {

    @Modifying
    @Transactional
    @Query("update Book b set b.status = ?1 where id = ?2")
    int updateByJPQL(int status, long id);


    @Modifying
    @Transactional
    @Query("delete from Book b where b.id = ?1")
    int deleteByJPQL(long id);
}

业务逻辑层service

Spring Boot+JPA+Mysql--事务操作_第2张图片

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;
    /**
     * 测试事务操作方法
     * @param id
     * @param status
     * @param uid
     * @return
     */
    @Transactional
    public int deleteAndUpdate(long id, int status, long uid) {

        int dcount = bookRepository.deleteByJPQL(id);
        int ucount = bookRepository.updateByJPQL(status,uid);
        return dcount+ucount;
    }

}

web层

Spring Boot+JPA+Mysql--事务操作_第3张图片

@RestController
@RequestMapping("/api/v1")
public class BookApp {

    @Autowired
    private BookService bookService;
    @PostMapping("/books/by")
    public int findBy(@RequestParam long id,@RequestParam int status,@RequestParam long uid) {
//        return bookService.findByAuthor(author);
//        return bookService.findByAuthorAndStatus(author, status);
        //return bookService.findByDescriptionEndsWith(description);

        //return bookService.findByJPQL(len);

//        return bookService.updateByJPQL(status, id);
//        return bookService.deleteByJPQL(id);
        return bookService.deleteAndUpdate(id, status, uid);
    }

}

测试:

 

修改前

Spring Boot+JPA+Mysql--事务操作_第4张图片

删除id为6的数据,修改id为5的status字段

Spring Boot+JPA+Mysql--事务操作_第5张图片

修改后

Spring Boot+JPA+Mysql--事务操作_第6张图片

 

控台打印

Spring Boot+JPA+Mysql--事务操作_第7张图片

你可能感兴趣的:(#,Spring,Boot,CSDN,李仁密)