实体类:model层
import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; /** * @ClassName Users * @Author: * @Description: * @Date:2021/8/5 16:54 * @Version:1.0 **/ @Entity @Data @Table(name="t_users") public class Users { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "主键id") private Long id; @Column(name = "username") @ApiModelProperty(value = "姓名") private String userName; @Column(name = "userage") @ApiModelProperty(value = "年龄") private Long userAge; @ManyToOne(cascade = CascadeType.PERSIST) //表示多方 @JoinColumn(name ="role_id") //维护一个外键,外键在Users一侧 private Roles roles; @Override public String toString() { return "Users{" + "id=" + id + ", userName='" + userName + '\'' + ", userAge=" + userAge + ", roles=" + roles + '}'; } } import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.persistence.*; import java.nio.charset.Charset; import java.util.HashSet; import java.util.Set; /** * @ClassName Roles * @Author: * @Description: * @Date:2021/8/17 16:54 * @Version:1.0 **/ @Entity @Data @Table(name="t_roles") public class Roles { @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.IDENTITY) @ApiModelProperty(value = "主键id") private Long id; @Column(name = "rolename") @ApiModelProperty(value = "角色名称") private String roleName; @OneToMany(mappedBy = "roles") private Set<Users> users=new HashSet<>(); @Override public String toString() { return "Roles{" + "id=" + id + ", roleName='" + roleName + '\'' + ", users=" + users + '}'; } }
jpa接口继承类:repository层
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * @author * @Date 2021/8/5 14:30 * */ public interface UsersRepository extends JpaRepository<Users, Long>,JpaSpecificationExecutor<Users> { } import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /** * @author * @Date 2021/8/5 14:30 * */ public interface RolesRepository extends JpaRepository<Roles, Long>,JpaSpecificationExecutor<Roles> { }
具体的接口:service层
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
/**
* @ClassName UsersService
* @Author:
* @Description:
* @Date:2021/8/6 11:24
* @Version:1.0
**/
public interface UsersService {
/**
* 查询所有
*
* @return List<Users>
*/
List<Users> findAll();
/**
* 查询所有:分页
* @param pageIndex :从第几页开始查询,从0开始
* @param pageSize :每页显示得条数
* @return Map<String,Object>
*/
Map<String,Object> findAll(int pageIndex, int pageSize);
/**
* 通过id查找
* @param userId
* @return Users
*/
Users findById(@NotNull Long userId);
/**
* 新增用户
* @param users
* @return Boolean
*/
Boolean addUser(@NotNull Users users);
/**
* 更新用户
* @param users
* @return Boolean
*/
Boolean updateUser(@NotNull Users users);
/**
* 删除用户
* @param userId
*
*/
void delteUser(@NotNull Long userId);
}
Dto层:封装web页面传递的接口参数
import lombok.Data; import me.zhengjie.base.BaseDTO;//可忽略,定义了一些公共参数,如操作者、更新者、创建时间、更新时间 import java.io.Serializable; /** * @ClassName UsersDto * @Author: * @Description: * @Date:2021/8/9 14:21 * @Version:1.0 **/ @Data public class UsersDto extends BaseDTO implements Serializable { private Long id; private String userName; private Long userAge; }
Imp层:具体的接口实现
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * @ClassName UsersServiceImpl * @Author: * @Description: * @Date:2021/8/6 11:29 * @Version:1.0 **/ @Service public class UsersServiceImpl implements UsersService { @Autowired UsersRepository usersRepository; @Override public List <Users> findAll() { //Order 定义了排序规则 Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id"); //Sort对象封装了排序规则 Sort sort=Sort.by(order); List <Users> usersList = usersRepository.findAll(sort); return usersList; } @Override public Map<String,Object> findAll(int pageIndex, int pageSize ) { //Order 定义了排序规则 Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id"); //Sort对象封装了排序规则 Sort sort=Sort.by(order); Pageable pageable = PageRequest.of( pageIndex, pageSize ,sort); Page<Users> page = usersRepository.findAll( pageable ); List <Users> usersList = page.getContent(); Map <String, Object> result = new HashMap<>(); result.put( "totalElements", page.getTotalElements() ); result.put( "totalPages", page.getTotalPages() ); result.put( "users", usersList ); return result; } @Override public Users findById(Long userId) { Optional <Users> optionalUsers = usersRepository.findById( userId ); if (optionalUsers.isPresent()) { Users users = optionalUsers.get(); return users; } else { return null; } } @Override public Boolean addUser(Users users) { Users users1 = usersRepository.save( users ); Boolean result = false; if (users1 != null) { result = true; } return result; } @Override public Boolean updateUser(Users users) { Optional <Users> optionalUsers = usersRepository.findById( users.getId() ); Boolean result = false; if (optionalUsers.isPresent()) { Users users1 = usersRepository.save( users ); if (users1 != null) { result = true; } return result; } else { return null; } } @Override public void delteUser(Long userId) { usersRepository.deleteById( userId ); } }
Controller层:
import com.google.common.base.Strings; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import me.zhengjie.uranus.component.service.dto.ResponseDto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName UsersContoller * @Author: * @Description: * @Date:2021/8/6 11:39 * @Version:1.0 **/ @RestController @RequiredArgsConstructor @RequestMapping("/api/user") @Slf4j public class UsersContoller { @Autowired UsersService usersService; @GetMapping("/list") @ResponseBody public ResponseDto list() { List <Users> usersList = usersService.findAll(); Integer count = usersList.size(); Map<String, Object> result = new HashMap<>(); result.put("count", count); result.put("users", usersList); return new ResponseDto(true, result); } @GetMapping("/list/{pageIndex}/{pageSize}") @ResponseBody public ResponseDto list1(@PathVariable("pageIndex") int pageIndex,@PathVariable("pageSize") int pageSize) { if((pageIndex>=0) && (pageSize>0)){ Map <String, Object> result=usersService.findAll( pageIndex,pageSize ); return new ResponseDto( true, result ); }else{ return new ResponseDto( false, "参数异常" ); } } @GetMapping("/findOne/{userId}") @ResponseBody public ResponseDto findById(@PathVariable("userId") Long userId) { Users users = usersService.findById( userId ); return new ResponseDto(true, users); } @PostMapping("/add") @ResponseBody public ResponseDto add(@RequestBody UsersDto usersDto) { String userName=usersDto.getUserName(); Long userAge=usersDto.getUserAge(); //对参数进行判断处理 if (Strings.isNullOrEmpty(userName)) { return new ResponseDto(false, "用户名称未填写"); } if (userAge <= 0) { return new ResponseDto(false, "年龄必须大于0"); } Users users = new Users(); users.setUserName( userName ); users.setUserAge( userAge ); Boolean result = usersService.addUser( users ); if (!result) { return new ResponseDto(false, "用户添加失败"); } return new ResponseDto(true, "用户添加成功"); } @PostMapping("/update") @ResponseBody public ResponseDto update(@RequestBody UsersDto usersDto) { Long userId=usersDto.getId(); String userName=usersDto.getUserName(); Long userAge=usersDto.getUserAge(); //对参数进行判断处理 if (Strings.isNullOrEmpty(userName)) { return new ResponseDto(false, "用户名称未填写"); } if (userAge <= 0) { return new ResponseDto(false, "年龄必须大于0"); } Users users = new Users(); users.setId( userId ); users.setUserName( userName ); users.setUserAge( userAge ); Boolean result = usersService.updateUser( users ); if (!result) { return new ResponseDto(false, "用户编辑失败"); } return new ResponseDto(true, "用户编辑成功"); } @GetMapping("/delete/{userId}") @ResponseBody public ResponseDto delete(@PathVariable("userId") Long userId) { try { usersService.delteUser( userId ); return new ResponseDto(true, "用户删除成功"); } catch (Exception e) { return new ResponseDto(false, "用户删除失败"); } } }
测试类:Test
import com.alibaba.fastjson.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @ClassName UsersTest * @Author: * @Description: * @Date:2021/8/6 10:32 * @Version:1.0 **/ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class UsersTest { @Autowired private MockMvc mockMvc; @Autowired private UsersRepository usersRepository; /*排序功能*/ @Test public void testSort(){ //Order 定义了排序规则 Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id"); //Sort对象封装了排序规则 Sort sort=Sort.by(order); List<Users> list= this.usersRepository.findAll(sort); for (Users users:list){ System.out.println(users); } } /*分页功能*/ @Test public void testPage(){ int pageIndex=1; int pageSize=5; Pageable pageable=PageRequest.of(pageIndex,pageSize); Page<Users> page=this.usersRepository.findAll(pageable); System.out.println( "总条数:"+page.getTotalElements() ); System.out.println( "总页数:"+page.getTotalPages() ); List<Users> list=page.getContent(); for (Users users:list){ System.out.println(users); } } /*分页+排序功能*/ @Test public void testPageAndSort(){ //Order 定义了排序规则 Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id"); //Sort对象封装了排序规则 Sort sort=Sort.by(order); int pageIndex=1; int pageSize=5; Pageable pageable=PageRequest.of(pageIndex,pageSize,sort); Page<Users> page=this.usersRepository.findAll(pageable); System.out.println( "总条数:"+page.getTotalElements() ); System.out.println( "总页数:"+page.getTotalPages() ); List<Users> list=page.getContent(); for (Users users:list){ System.out.println(users); } } /*多条件查询*/ @Test public void testCombinedQuery(){ /** * 匿名内部类 * 自定义查询条件 * 1、实现Specification接口(提供泛型,查询的对象实体类) * 2、实现toPredicate方法(该方法用于构造查询条件) * 3、需要借助方法中的两个参数 * Root<T> root:获取需要查询的对象属性 * CriteriaQuery<T> query:顶层查询对象(了解,一般不用) * CriteriaBuilder cb:构造查询条件,内容封装了很多查询方式(模糊匹配、精准匹配...) * */ //单个查询条件 Specification<Users> spec = new Specification <Users>() { @Override public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { // where userName like "%战狼%" Predicate predicate=criteriaBuilder.like( root.get( "userName" ),"%战狼%" ); return predicate; } }; List<Users> usersList=this.usersRepository.findAll( spec ); for (Users users:usersList){ System.out.println(users); } //多个查询条件 Specification<Users> spec1 = new Specification <Users>() { @Override public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { // where userName like "%战狼%" and userAge=3 Predicate p1=criteriaBuilder.like( root.get( "userName" ),"%战狼%" ); Predicate p2=criteriaBuilder.equal( root.get( "userAge" ),1 ); return criteriaBuilder.and( p1,p2 ); } }; List<Users> usersList1=this.usersRepository.findAll( spec1 ); for (Users users:usersList1){ System.out.println(users); } } /*多条件查询*/ @Test @Test public void testFindAll(){ MockHttpServletRequestBuilder get=MockMvcRequestBuilders.get( "/user/list" ); try { MvcResult mvcResult = mockMvc.perform( get ).andReturn(); int status=mvcResult.getResponse().getStatus(); System.out.println( "响应码="+status ); String result=mvcResult.getResponse().getContentAsString(); System.out.println( "响应体="+result ); } catch (Exception e) { e.printStackTrace(); } } @Test public void testFindById(){ MockHttpServletRequestBuilder post=MockMvcRequestBuilders.post( "/user/findOne" ) .contentType( MediaType.APPLICATION_FORM_URLENCODED_VALUE ) .param( "userId","3L" ) .characterEncoding( "utf-8" ) .accept(MediaType.APPLICATION_JSON_UTF8_VALUE); try { MvcResult mvcResult = mockMvc.perform( post ).andReturn(); int status=mvcResult.getResponse().getStatus(); System.out.println( "响应码="+status ); String result=mvcResult.getResponse().getContentAsString(); System.out.println( "响应体="+result ); } catch (Exception e) { e.printStackTrace(); } } @Test public void testAdd(){ UsersDto usersDto=new UsersDto(); usersDto.setUserName( "战狼" ); usersDto.setUserAge( 2L ); MockHttpServletRequestBuilder post=MockMvcRequestBuilders.post( "/user/add" ) .contentType( MediaType.APPLICATION_JSON ) .content( JSONObject.toJSONString(usersDto) ); try { MvcResult mvcResult = mockMvc.perform( post ).andReturn(); int status=mvcResult.getResponse().getStatus(); System.out.println( "响应码="+status ); String result=mvcResult.getResponse().getContentAsString(); System.out.println( "响应体="+result ); } catch (Exception e) { e.printStackTrace(); } } @Test public void testUpdate(){ Users users=new Users(); users.setId( 1L ); users.setUserName( "张三89" ); users.setUserAge( 29L ); MockHttpServletRequestBuilder post=MockMvcRequestBuilders.post( "/user/update/1" ) .contentType( MediaType.APPLICATION_JSON ) .content( JSONObject.toJSONString(users) ); try { MvcResult mvcResult = mockMvc.perform( post ).andReturn(); int status=mvcResult.getResponse().getStatus(); System.out.println( "响应码="+status ); String result=mvcResult.getResponse().getContentAsString(); System.out.println( "响应体="+result ); } catch (Exception e) { e.printStackTrace(); } } @Test public void addUser(){ Users users=new Users(); users.setUserName( "破冰行动" ); users.setUserAge( 1L ); Roles roles=new Roles(); roles.setRoleName( "电影" ); roles.getUsers().add(users ); users.setRoles( roles ); usersRepository.save( users ); } }
jpa其他用法:
查询所有-不分页 @Override public List<AutoCaseDebugInfoDto> findAll() { //Order 定义了排序规则 Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id"); //Sort对象封装了排序规则 Sort sort = Sort.by(order); List<AutoCaseDebugInfo> caseList = autoCaseDebugInfoRepository.findAll(sort); List<AutoCaseDebugInfoDto> caseDtoList = new ArrayList<>(); for (AutoCaseDebugInfo autoCaseDebugInfo : caseList) { AutoCaseDebugInfoDto autoCaseDebugInfoDto = new AutoCaseDebugInfoDto(); autoCaseDebugInfoDto.convert(autoCaseDebugInfo); caseDtoList.add(autoCaseDebugInfoDto); } return caseDtoList; } 查询所有-分页 @Override public Map<String, Object> findAll(@NotNull int pageIndex, @NotNull int pageSize) { //Order 定义了排序规则 Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id"); //Sort对象封装了排序规则 Sort sort = Sort.by(order); Pageable pageable = PageRequest.of(pageIndex, pageSize, sort); Page<AutoCaseDebugInfo> page = autoCaseDebugInfoRepository.findAll(pageable); List<AutoCaseDebugInfo> caseList = page.getContent(); List<AutoCaseDebugInfoDto> caseDtoList = new ArrayList<>(); for (AutoCaseDebugInfo autoCaseDebugInfo : caseList) { AutoCaseDebugInfoDto autoCaseDebugInfoDto = new AutoCaseDebugInfoDto(); autoCaseDebugInfoDto.convert(autoCaseDebugInfo); caseDtoList.add(autoCaseDebugInfoDto); } Map<String, Object> result = new HashMap<>(); result.put("total", page.getTotalElements()); result.put("totalPages", page.getTotalPages()); result.put("page", pageIndex + 1); result.put("size", pageSize); result.put("list", caseDtoList); return result; }
@GetMapping("/list") @ResponseBody public ResponseDto list() { List <AutoCaseDebugInfoDto> autoCaseDebugInfoDtoList = autoCaseDebugInfoService.findAll(); Integer totalElements = autoCaseDebugInfoDtoList.size(); Map <String, Object> result = new HashMap <>(); result.put( "total", totalElements ); result.put( "list", autoCaseDebugInfoDtoList ); return new ResponseDto( true, result ); }
@GetMapping("/list/{pageIndex}/{pageSize}") @ResponseBody public ResponseDto list1(@PathVariable("pageIndex") int pageIndex, @PathVariable("pageSize") int pageSize) { if ((pageIndex >= 0) && (pageSize > 0)) { Map <String, Object> result = autoCaseDebugInfoService.findAll( pageIndex, pageSize ); return new ResponseDto( true, result ); } else { return new ResponseDto( false, "参数异常" ); } }
建表语句:
CREATE TABLE `t_users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`username` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '姓名',
`userage` bigint(20) DEFAULT NULL COMMENT '年龄',
`role_id` bigint(20) DEFAULT NULL COMMENT '角色id',
PRIMARY KEY (`id`),
UNIQUE KEY `UK` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='用户信息表';
CREATE TABLE `t_roles` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
`rolename` varchar(255) DEFAULT NULL COMMENT '角色名称',
PRIMARY KEY (`id`),
UNIQUE KEY `UK` (`rolename`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='角色信息表';