spring boot 整合 jpa (二) -- 之数据操作

版权声明:[ws - 兮的博客] - 空间专属,未经声明不得私自转载 https://blog.csdn.net/qq_41463655/article/details/82939560

spring boot 整合 jpa (一) – 之基础配置
https://blog.csdn.net/qq_41463655/article/details/82939481
spring boot 整合 jpa (三) – 之表关系映射
https://blog.csdn.net/qq_41463655/article/details/82939791

dao层

package ws.cn.jpa.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Component;
import ws.cn.jpa.entity.User;

/**
 * Created by Administrator on 2018/10/2/002.
 * JpaRepository<User,Long> 说明:
 * User 实体类
 * Long 实体类主建的数据类型
 */

@Component
public interface UserDao extends JpaRepository<User,Long>,JpaSpecificationExecutor<User> {

    //自定义 sql 语句
    @Query(value = "SELECT * FROM USER WHERE id = ?1", nativeQuery = true)
    User selectId(Integer id);

  /*
    * 我们在这里直接继承 JpaRepository
    * 这里面已经有很多现成的方法
    * 这也是JPA的一大优点
    *
    *  (1) CrudRepository: 继承 Repository,实现了一组 CRUD 相关的方法
       (2) PagingAndSortingRepository: 继承 CrudRepository,实现了一组分页排序相关的方法
       (3)JpaRepository: 继承 PagingAndSortingRepository,实现一组 JPA 规范相关的方法
       (4)JpaSpecificationExecutor: 实现条件查询
    * */

}

此处直接调用的 dao 层,请自行把复杂代码防止 service层在用 contrller 层调用

package ws.cn.jpa.controller;

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.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ws.cn.jpa.dao.UserDao;
import ws.cn.jpa.entity.User;

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.List;

/**
 * Created by Administrator on 2018/10/2/002.
 */
@RestController
public class UserController {
    //带 Flush 的方法为sql 立即生效

/*    @Autowired
    private UserService userService;*/

    @Autowired
    private UserDao userDao;

    //============查询所有===============
    @GetMapping("/listuser")
    public List<User> findAll() {
        // Sort  第一个属性为排序规则, 第二个属性为按照那个字段来排序
        Sort sort = new Sort(Sort.Direction.DESC, "userId");
        //findAll() 可以不带sort属性,默认排序
        return userDao.findAll(sort);
    }

    //============ id 查询===============
    @GetMapping("/findById")
    public User findById(Long id) {
        id = 3L;   //模拟 id
        User user = userDao.findById(Long.valueOf(id)).get();
        return user;
    }

    //============ 多id 查询===============
    @GetMapping("/findAllById")
    public List findAllById(List<Long> ids) {
        // 模拟 id
        List list = new ArrayList();
        list.add(Long.valueOf(2));
        list.add(Long.valueOf(3));
        List users = userDao.findAllById(list);
        return users;
    }

    //============ 分页查询===============
    @GetMapping("/pageuser")
    public Page<User> pageuser() {
        // 开始页数 / 每页数量 / 排序规则 / 根据id排序
        Pageable pageable = new PageRequest(0, 2, Sort.Direction.DESC, "id");
        Page<User> page = userDao.findAll(pageable);
        System.out.println(page.getTotalElements() + "-->总数据数"+"/r/n"+
                page.getTotalPages() + "-->总页数"+"/r/n"+
                page.getNumber() + "-->当前页"+"/r/n"+
                page.getSize() + "-->每页条数"+"/r/n"+
                page.getNumberOfElements() + "-->本页条数"+"/r/n"+
                "查询到的数据:" + page.getContent()
        );
        return page;
    }

    //============ 动态条件查询 ===============
    /*
     *  username = 666 and  password = 666
     *  username = 666 or   password = 666
     **/
    @GetMapping("/queryStudent")
    public List<User> queryStudent(User user) {
        user.setUsername("666");
        user.setPassword("666");
        //生成条件
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                // and 条件
                List<Predicate> ands = new ArrayList<>();
                if (user.getUsername() != null && !"".equals(user.getUsername())) {
                    ands.add(criteriaBuilder.equal(root.<String>get("username"), user.getUsername()));
                }
                if (user.getUsername() != null && !"".equals(user.getUsername())) {
                    ands.add(criteriaBuilder.equal(root.<String>get("password"), user.getPassword()));
                }
                // or 条件
                List<Predicate> ors = new ArrayList<>();
                ors.add(criteriaBuilder.like(root.<String>get("username"), "%"+"9"+"%")); //模糊查询 like
                ors.add(criteriaBuilder.like(root.<String>get("password"), "%"+"9"+"%")); //模糊查询 like

                Predicate and = criteriaBuilder.and(ands.toArray(new Predicate[ands.size()])); //and 连接的条件集
                Predicate or = criteriaBuilder.or(ors.toArray(new Predicate[ors.size()]));     //or 连接的条件集

                List<Predicate> predicate = new ArrayList<>(); //条件集集合
                predicate.add(and); //添加 and 的条件集
                predicate.add(or);  //添加 or 的条件集

                //return criteriaBuilder.and(predicate.toArray(new Predicate[predicate.size()]));// and 连接条件集
                return criteriaBuilder.or(predicate.toArray(new Predicate[predicate.size()]));  // or  连接条件集
            }
        };
        List userDaoAll = userDao.findAll(specification);
        return userDaoAll;
    }


    //============ 添加、修改数据===============
    @GetMapping("/adduser")
    public void addUser(User user) {
        userDao.save(user);
    }



    //============ 添加多条数据===============
    @GetMapping("/saveAll")
    public void saveAll() {
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User("mm" + i, "123456");
            list.add(user);
        }
        //保存实体集合
        userDao.saveAll(list);
    }

    //============ id 删除数据===============
    @GetMapping("/deleteId")
    public void deleteuser(Long id) {
        userDao.deleteById(id);
    }

    //============ 多 id 删除数据===============
    @GetMapping("/deleteIds")
    public void deleteAll(List<Long> ids) {
        List list = new ArrayList();
        list.add(Long.valueOf(7));
        list.add(Long.valueOf(8));
        list.add(Long.valueOf(9));
        userDao.deleteAll(list);
    }

    //============ 删除所有数据 ===============
    @GetMapping("/deleteAll")
    public void deleteAll(Long id) {
        userDao.deleteAll();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41463655/article/details/82939560