一、前置条件
确定使用的IDE是IntelliJ IDEA;
确保已经创建了一个Spring MVC的web工程;
确保已经配置好了Layui相关的静态资源。
二、添加依赖
添加spring-data-jpa、MySQL JDBC驱动、Spring Web MVC等依赖。
org.springframework
spring-webmvc
${spring.version}
org.springframework.data
spring-data-jpa
${spring-data.version}
mysql
mysql-connector-java
${mysql-connector.version}
三、创建数据表格
使用Layui实现一个数据表格,并添加搜索功能。
四、添加Controller
创建UserController,添加查询用户数据的方法。
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/query")
@ResponseBody
public Result query(UserSearchCondition condition) {
Page
page = userService.findByCondition(condition);
return Result.success(page);
}
}
// UserSearchCondition.java
@Data
public class UserSearchCondition {
private Integer page = 1;
private Integer limit = 10;
private String key;
public Pageable getPageable() {
return PageRequest.of(page - 1, limit);
}
}
// UserService.java
public interface UserService {
Page findByCondition(UserSearchCondition condition);
}
// UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository repository;
@Override
public Page findByCondition(UserSearchCondition condition) {
UserSpecification specification = new UserSpecification(condition);
return repository.findAll(specification, condition.getPageable());
}
}
// UserSpecification.java
public class UserSpecification implements Specification {
private UserSearchCondition condition;
public UserSpecification(UserSearchCondition condition) {
this.condition = condition;
}
@Override
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder cb) {
List predicates = new ArrayList<>();
if (StringUtils.isNotEmpty(condition.getKey())) {
String pattern = "%" + condition.getKey() + "%";
Predicate usernameLike = cb.like(root.get("username"), pattern);
Predicate emailLike = cb.like(root.get("email"), pattern);
Predicate phoneLike = cb.like(root.get("phone"), pattern);
predicates.add(cb.or(usernameLike, emailLike, phoneLike));
}
return cb.and(predicates.toArray(new Predicate[0]));
}
}
五、编写SQL脚本
创建user表,并向表中添加一些测试数据。例如:
CREATE TABLE user (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(32) NOT NULL COMMENT '用户名',
email varchar(64) NOT NULL COMMENT '邮箱',
phone varchar(16) NOT NULL COMMENT '手机',
password varchar(64) NOT NULL COMMENT '密码',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户信息表';
INSERT INTO user (id, username, email, phone, password, create_time, update_time)
VALUES
(1, 'admin', 'admin@qq.com', '13800138000', '123456', '2021-09-15 16:14:12', '2021-09-15 16:14:12'),
(2, 'tom', 'tom@qq.com', '13900139000', '123456', '2021-09-15 16:14:36', '2021-09-15 16:14:36'),
(3, 'jack', 'jack@qq.com', '13600136000', '123456', '2021-09-15 16:14:49', '2021-09-15 16:14:49');