Spring Boot+JPA+Mysql--自定义更新

只更新某一个字段,如果使用JPA默认的xx.save(book),方法会更新所有的字段,如果不传值默认为null

根据id更新status字段 sql(updata book set status=1 where id=20),根据id删除某条信息

数据访问层

public interface BookRepository extends JpaRepository<Book,Long> {

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

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

业务逻辑层service

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;
    /**
     * 自定义更新
     * @param status
     * @param id
     * @return
     */
    @Transactional
    public int updateByJPQL(int status, long id) {

        return bookRepository.updateByJPQL(status, id);
    }
    /**
     * 自定义删除
     * @param id
     * @return
     */
    @Transactional
    public int deleteByJPQL(long id) {

        return bookRepository.deleteByJPQL( id);
    }

}

web层

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

    @Autowired
    private BookService bookService;
    @PostMapping("/books/by")
    public int findBy(@RequestParam int status,@RequestParam long id) {
//        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);
    }
}

测试更新

更新前

更新后

控制台输出:

发布了153 篇原创文章 · 获赞 6 · 访问量 2355

猜你喜欢

转载自blog.csdn.net/yangshengwei230612/article/details/103765238