springBoot整合springdata Jpa的基本使用以及带条件的分页查询

一、springBoot整合springData Jpa

在application.properties中声明启用如下:

spring.datasource.name=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mst?useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.aliba
#Spring Data JPA
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql=trueba.druid.pool.DruidDataSource

开启springData Jpa自动配置

pom.xml文件


            org.springframework.boot
            spring-boot-starter-data-jpa
        

这里使用的Druid数据源,则创建配置类

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return  new DruidDataSource();
    }

    /**
     * 配置Druid的监控
     *     1、配置一个管理后台的Servlet
     */

    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        Map initParams = new HashMap<>(5);

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        //默认就是允许所有访问
        initParams.put("allow","");
        initParams.put("deny","localhost");

        bean.setInitParameters(initParams);
        return bean;
    }


    /**
     * 2、配置一个web监控的filter
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());

        Map initParams = new HashMap<>(5);
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Collections.singletonList("/*"));

        return  bean;
    }

}

二、jpa基本使用

1.方法名的使用

只要满足一定的规范,方法名即可操作数据库。如:

public interface UserDao extends JpaRepository, JpaSpecificationExecutor {
    /**
     * findUserByUsernameAndPassword
     * @param name name
     * @param password password
     * @return User
     */
    User findUserByLoginNameAndPassword(String name, String password);

    /**
     * updataPasswordById
     * @param id id
     * @param newPasseord newPasseord
     */
    @Modifying
    @Query("update User u set u.password=:newPasseord where u.id=:id")
    void updatePasswordById(@Param("id") Integer id, @Param("newPasseord") String newPasseord);

    /**
     * deleteUserById
     * @param id id
     */
    @Modifying
    void deleteUserById(Integer id);

    /**
     * findUserById
     * @param id id
     * @return User
     */
    User findUserById(Integer id);
}

如果你是用的idea则会提示。

注意:如果该方法是update或者delete必须在方法上加入注解@Modifying,insert不能使用该规范

2.@Query注解的使用

如果方法较为麻烦,或者参数不按方法的顺序,则可使用该注解

@Modifying
    @Query("update User u set u.password=:newPasseord where u.id=:id")
    void updatePasswordById(@Param("id") Integer id, @Param("newPasseord") String newPasseord);

三、Jpa的带条件分页使用

使用Specification方法实现分页功能,该方法dao层必须继承JpaSpecificationExecutor接口

/**
     * 获取menu list
     * @return  List
     *
     */
    @Override
    public List getMenuList(HttpServletRequest request) {
        String pid1 = request.getParameter("pid");
        int pid = (pid1 == null || "".equals(pid1.trim())) ?-1:Integer.parseInt(pid1);
        String menuName = request.getParameter("menuname");
        String url = request.getParameter("url");
        String icon = request.getParameter("icon");
        String page1 = request.getParameter("page");
        int page = (page1 == null || "".equals(page1.trim()))?-1:Integer.parseInt(page1);
        String rows1 = request.getParameter("rows");
        int rows = (rows1 == null || "".equals(rows1.trim()))?-1:Integer.parseInt(rows1);

        Specification specification = getMenuSpecification(pid, menuName, url, icon);
        int firstResult = (page -1) * rows;
        Pageable pageable = new PageRequest(firstResult, rows);
        return menuDao.findAll(specification,pageable).stream().collect(Collectors.toList());
    }

    /**
     * 带条件的分页查询
     * @param pid pid
     * @param menuName menuName
     * @param url url
     * @param icon icon
     * @return Specification
     */
    private Specification getMenuSpecification(int pid, String menuName, String url, String icon) {
        return (Specification) (root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = criteriaBuilder.conjunction();
            if (pid != -1) {
                predicate.getExpressions().add(criteriaBuilder.equal(root.get("pid"), pid));
            }
            if (menuName != null && !"".equals(menuName.trim())) {
                predicate.getExpressions().add(criteriaBuilder.equal(root.get("menuname"), menuName));
            }
            if (url != null && !"".equals(url.trim())) {
                predicate.getExpressions().add(criteriaBuilder.equal(root.get("url"), url));
            }
            if (icon != null && !"".equals(icon.trim())) {
                predicate.getExpressions().add(criteriaBuilder.equal(root.get("icon"), icon));
            }
            return predicate;
        };
    }

注意:stream().collect(Collectors.toList());

这个方法是Java jdk1.8以后的版本才有的

 

你可能感兴趣的:(Java,springBoot,SpringData,Java学习)