Spring Data JPA findBy
2018-10-20 本文已影响139人
技术小白熊
spring boot jpa 的高级用法,以及swagger 的使用
1、引入swagger应添加的jar包
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
2、在主程序中添加的注解
@SpringBootApplication
@EnableSwagger2Doc
public class QuickstartdemoApplication {
public static void main(String[] args) {
SpringApplication.run(QuickstartdemoApplication.class, args);
}
}
3、使用jpa中的findBy语法和方法名解析的repository
public interface SysUserRepository extends JpaRepository<SysUser,Integer> {
/**
* 根据账号精确查询
* @param account
* @return
*/
SysUser findByAccount(String account);
/**
* 根据昵称模糊查询
* @param nickname
* @return
*/
List<SysUser> findByNicknameStartingWith(String nickname);
/**
* 根据昵称模糊查询和粉丝数查询
* @param nickname
* @param fans
* @return
*/
List<SysUser> findByNicknameStartingWithAndFansAfter(String nickname,Integer fans);
// @Query("from SysUser u where u.password.length=:lenght")
// List<SysUser> findByPasswordLength(@Param("length") Integer length);
@Query("from SysUser u where u.nickname=:nickname")
SysUser findUser(@Param("nickname") String nickname);
@Query("from SysUser u where u.nickname like %:nickname% order by u.fans desc")
List<SysUser> findUsers(@Param("nickname") String nickname);
}
4、service层
public interface SysUserService {
List<SysUser> findAll();
SysUser findOne(Integer id);
SysUser findOneByAccount(String account);
// List<SysUser> findByPasswordLength(Integer length);
List<SysUser> findOrderByFans(String nickname);
}
5、impl层
@Service
public class SysUserServiceImpl implements SysUserService {
@Resource
private SysUserRepository sysUserRepository;
@Override
public List<SysUser> findAll() {
return sysUserRepository.findAll();
}
@Override
public SysUser findOne(Integer id) {
return sysUserRepository.findById(id).get();
}
@Override
public SysUser findOneByAccount(String account) {
return sysUserRepository.findByAccount(account);
}
// @Override
// public List<SysUser> findByPasswordLength(Integer length) {
// return sysUserRepository.findByPasswordLength(length);
// }
@Override
public List<SysUser> findOrderByFans(String nickname) {
return sysUserRepository.findUsers(nickname);
}
}
6、controller层
@RestController
@RequestMapping(value = "/user")
public class SysUserController {
@Resource
private SysUserService sysUserService;
@GetMapping(value = "/all")
public List<SysUser> findAll(){
return sysUserService.findAll();
}
@GetMapping(value = "/oneId/{id}")
public SysUser getOne(@PathVariable("id") Integer id){
return sysUserService.findOne(id);
}
@GetMapping(value = "/account/{account}")
public SysUser getOneByNickname(@PathVariable("account") String account){
return sysUserService.findOneByAccount(account);
}
@GetMapping(value = "/nickname/{nickname}")
public List<SysUser> findOrderByFans(@PathVariable("nickname") String nickname){
return sysUserService.findOrderByFans(nickname);
}
}