JPA排序 分页 条件查询 选择更新

package com.hy.jpa;

import com.hy.jpa.entity.User;
import com.hy.jpa.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;

import java.util.List;

@SpringBootTest
class JpaApplicationTests {
    @Autowired
    private UserRepository userRepository;

    @Test
    void contextLoads() {

        //Order	定义了排序规则
        Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id");
        //Sort对象封装了排序规则
        Sort sort=Sort.by(order);

        //Pageable:封装了分页的参数,当前页,每页显示的条数。注意:它的当前页是从0开始
        //PageRequest(page,size):page表示当前页,size表示每页显示多少条
        int pageSize = 2;
        int pageNum = 1;

        //条件查询
        User user = new User();
        user.setUserName("zhangsan");
        ExampleMatcher matcher = ExampleMatcher.matching()
            .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.startsWith())//模糊查询匹配开头,即{username}%
            .withMatcher("address" ,ExampleMatcher.GenericPropertyMatchers.contains())//全部模糊查询,即%{address}%
            .withIgnorePaths("password");//忽略字段,即不管password是什么值都不加入查询条件
        Example<User> example = Example.of(user, matcher);

        //分页查询
        Pageable pageable= PageRequest.of(pageNum,pageSize);
        Page<User> page=userRepository.findAll(example,pageable);

        //获取当前页的数据
        List<User> list=page.getContent();

        System.out.println("数据的总条数:"+page.getTotalElements());
        System.out.println("总页数:"+page.getTotalPages());
        System.out.println("当前页条数"+page.getNumberOfElements());

        //选择更新
        User newObj = new User();
        newObj.setUserId(1L);
        newObj.setUserName("法外狂徒");
        Optional<User> optionalUser = userRepository.findById(newObj.getUserId());
        User dbUser = optionalUser.get();

        SpringUtils.copyPropertiesIgnoreNull(newObj,dbUser);
        userRepository.save(dbUser);


    }

}

SpringUtils

package com.hy.jpa.util;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashSet;
import java.util.Set;

public class SpringUtils implements ApplicationContextAware {

    /**
     * 当前IOC
     *
     */
    private static ApplicationContext applicationContext;

    /**
     * * 设置当前上下文环境,此方法由spring自动装配
     *
     */
    @Override
    public void setApplicationContext(ApplicationContext arg0)
            throws BeansException {
        applicationContext = arg0;
    }

    /**
     * 从当前IOC获取bean
     *
     * @param id
     * bean的id
     * @return
     *
     */
    public static Object getObject(String id) {
        Object object = null;
        object = applicationContext.getBean(id);
        return object;
    }

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyPropertiesIgnoreNull(Object src, Object target){
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
    }

}

这里插个眼,方便以后看
Spring Data JPA实现动态条件与范围查询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值