CrudRepository接口的使用
CrudRepository接口,主要完成一些增删改查的操作。
注意:CrudRepository接口继承Repository接口
1、持久层接口:
package com.gblfy.repository;import com.gblfy.pojo.Users;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;public interface UserRepositoryCrudRepository extends CrudRepository<Users,Integer> {
}
2、测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryCrudRepositoryTest {@Autowiredprivate UserRepositoryCrudRepository userRepositoryCrudRepository;//保存客户数据@Testpublic void saveUsers() {Users u = new Users();u.setName("guobin");u.setAge(25);u.setAddress("zhongguohaidian");userRepositoryCrudRepository.save(u);}//更新客户数据//和保存数据是一个save方法,// 这个方法先判断是不是同一个实体类或者同一个对象,// 如果是执行更新操作,如果不是,就执行保存操作@Testpublic void updateSave() {Users u = new Users();u.setId(5);u.setName("guobin");u.setAge(25);u.setAddress("zhongguohaidian");userRepositoryCrudRepository.save(u);}/*** 通过id查找数据*/@Testpublic void findById() {Optional<Users> users = userRepositoryCrudRepository.findById(5);System.out.println(users);}/*** 查询全部数据*/@Testpublic void findAll() {Iterable<Users> list = userRepositoryCrudRepository.findAll();for (Users users : list) {System.out.println(users);}}/*** 通过id删除数据*/@Testpublic void deleteById() {this.userRepositoryCrudRepository.deleteById(5);}
}
本文源码下载:
github地址:
https://github.com/gb-heima/Spring-Boot-Actual-Combat/tree/master/parent/spring-boot-chapter-9