SpringBoot项目中分页功能后端实现
控制层
@Controller
@RequestMapping("/admin/types")
public class TypeController {
@Autowired
private TypeService typeService;
@RequestMapping
public String list(@PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable, Model model){
Page<Type> page = typeService.listType(pageable);
model.addAttribute("page",page);
return "admin/types";
}
}
dao层
package com.zr.dao;
import com.zr.po.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository<User, Long> {
User findByUsernameAndPassword(String username, String password);
// void findByUsernameAndPassword(String username, String password);
}
package com.zr.dao;
import com.zr.po.Type;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TypeDao extends JpaRepository<Type, Long> {
}
service层
interface:
package com.zr.service;
import com.zr.po.User;
public interface UserService {
User checkUser(String username, String password);
}
package com.zr.service;
import com.zr.po.Type;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface TypeService {
Page<Type> listType(Pageable pageable);
}
实现方法
package com.zr.service.impl;
import com.zr.dao.UserDao;
import com.zr.po.User;
import com.zr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User checkUser(String username, String password) {
return userDao.findByUsernameAndPassword(username, password);
// return null;
}
}
package com.zr.service.impl;
import com.zr.dao.TypeDao;
import com.zr.po.Type;
import com.zr.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@Service
public class TypeServiceImpl implements TypeService {
@Autowired
private TypeDao typeDao;
@Override
public Page<Type> listType(Pageable pageable) {
return typeDao.findAll(pageable);
// return null;
}
}
实体类
用于和数据库的表对应
@Entity
@Table(name = "t_type")
public class Type {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "type")
private List<News> news = new ArrayList<>();
public Type() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<News> getNews() {
return news;
}
public void setNews(List<News> news) {
this.news = news;
}
@Override
public String toString() {
return "Type{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}