Spring Boot入门教程:十四、spring boot 2.0 整合 jpa 进阶

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LDY1016/article/details/83539877

spring boot 2.0 + jpa 基础整合请查看:八、spring boot 2.0 整合 jpa

本文主要针对jpa常见的用法进行演示讲解,主要包括JPA常见的查询、分页查询、HQL操作、SQL操作等几个方面。

1、JPA支持的常用的查询

    /**
     * And查询 等价于SQL中的and<br>
     */
    List<UserEntity> findByNameAndAge(String name, Integer age);

    /**
     * Or查询 等价于SQL中的or<br>
     */
    List<UserEntity> findByNameOrAge(String name, Integer age);
	
    /** 
     * Between查询 等价于SQL中的between<br>
     */
    public List<UserEntity> findByAgeBetween(int min,int max);
 
    /**
     * LessThan查询 等价于SQL中的 "<"<br>
     */
    public List<UserEntity> findByAgeLessThan(int max);
 
    /**
     * GreaterThan查询 等价于SQL中的">"<br>
     */
    public List<UserEntity> findByAgeGreaterThan(int min);
 
    /**
     * IsNull查询 等价于SQL中的 "is null"<br>
     */
    public List<UserEntity> findByNameIsNull();
    
    /**
     * IsNotNull查询 等价于SQL中的 "is not null"<br>
     */
    public List<UserEntity> findByNameIsNotNull();
 
    /**
     * NotNull查询 与IsNotNull等价;
     */
    public List<UserEntity> findByNameNotNull();
 
    /**
     * Like查询 等价于SQL中的 "like";
     */
    public List<UserEntity> findByNameLike(String name);
 
    /**
     * NotLike查询 等价于SQL中的 "not like"
     */
    public List<UserEntity> findByNameNotLike(String name);
 
    /**
     * OrderBy查询 等价于SQL中的 "order by"
     */
    public List<UserEntity> findByNameNotNullOrderByAgeAsc();
 
    /**
     * Not查询 等价于SQL中的 "! ="
     */
    public List<UserEntity> findByNameNot(String name);
 
    /**
     * In查询 等价于SQL中的 "in";
     */
    public List<UserEntity> findByNameIn(String name);
 
    /**
     * NotIn查询 等价于SQL中的 "not in"
     */
    public List<UserEntity> findByNameNotIn(String name);

2、JPA的分页查询

    /**
     * 分页查询
     */
    Page<UserEntity> findByNameLike(String name,Pageable pageable);

3、HQL操作

    /**
     * HQL语句查询<br>
     */
    @Query("select u from UserEntity u where u.name = ?1 and u.age = ?2")
    List<UserEntity> findByHql(String user, Integer age);
	
    /**
     * HQL语句删除
     */
    @Query(value = "delete from UserEntity u where u.id=?1 ")
    @Modifying
    @Transactional
    public void deleteByHql(Integer id);
 
 
    /**
     * HQL修改
     */
    @Transactional
    @Query(value = "update UserEntity u set u.name=?1 where u.id=?2 ")
    @Modifying
    public void updateByHql(String name,int id);

4、SQL操作

    /**
     * 原生SQL进行查询<br>
     */
    @Query(value = "select u.* from  user u where u.name = ?1 and u.age = ?2", nativeQuery = true)
    public List<UserEntity> findBySql(String name, Integer age);
    
    /**
     * 原生的SQL删除
     */
    @Transactional
    @Query(value = "delete from user where id=?1", nativeQuery = true)
    @Modifying
    public void deleteBySql(int id);
 
 
    /**
     * 原生的SQL修改
     */
    @Query(value = "update user set name=?1 where id=?2", nativeQuery = true)
    @Modifying
    @Transactional
    public void updateBySql(String name,int id);
 
    /**
     * 原生的SQL插入
     */
    @Query(value = "insert into user(name,age) value(?1,?2)", nativeQuery = true)
    @Modifying
    @Transactional
    public void insertBySql(String name,int age);

5、完整代码

UserEntity.java

package com.ldy.bootv2.demo.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@Entity
@ApiModel
@Table(name="user")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"}) 
public class UserEntity implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
        @GeneratedValue
        @ApiModelProperty(value="id,新建时不传,修改时传")
	private Integer id;
	
	@Column
	@ApiModelProperty(value="名称")
	private String name;
	
	@Column
	@ApiModelProperty(value="年龄")
	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}

UserDao.java

package com.ldy.bootv2.demo.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.ldy.bootv2.demo.entity.UserEntity;

public interface UserDao extends JpaRepository<UserEntity, Integer> {
	
    /******************** 1、支持根据方法名自动适配查询的接口示例 *********************/

    /**
     * And查询 等价于SQL中的and<br>
     */
    List<UserEntity> findByNameAndAge(String name, Integer age);

    /**
     * Or查询 等价于SQL中的or<br>
     */
    List<UserEntity> findByNameOrAge(String name, Integer age);
	
    /** 
     * Between查询 等价于SQL中的between<br>
     */
    public List<UserEntity> findByAgeBetween(int min,int max);
 
    /**
     * LessThan查询 等价于SQL中的 "<"<br>
     */
    public List<UserEntity> findByAgeLessThan(int max);
 
    /**
     * GreaterThan查询 等价于SQL中的">"<br>
     */
    public List<UserEntity> findByAgeGreaterThan(int min);
 
    /**
     * IsNull查询 等价于SQL中的 "is null"<br>
     */
    public List<UserEntity> findByNameIsNull();
    
    /**
     * IsNotNull查询 等价于SQL中的 "is not null"<br>
     */
    public List<UserEntity> findByNameIsNotNull();
 
    /**
     * NotNull查询 与IsNotNull等价;
     */
    public List<UserEntity> findByNameNotNull();
 
    /**
     * Like查询 等价于SQL中的 "like";
     */
    public List<UserEntity> findByNameLike(String name);
 
    /**
     * NotLike查询 等价于SQL中的 "not like"
     */
    public List<UserEntity> findByNameNotLike(String name);
 
    /**
     * OrderBy查询 等价于SQL中的 "order by"
     */
    public List<UserEntity> findByNameNotNullOrderByAgeAsc();
 
    /**
     * Not查询 等价于SQL中的 "! ="
     */
    public List<UserEntity> findByNameNot(String name);
 
    /**
     * In查询 等价于SQL中的 "in";
     */
    public List<UserEntity> findByNameIn(String name);
 
    /**
     * NotIn查询 等价于SQL中的 "not in"
     */
    public List<UserEntity> findByNameNotIn(String name);
    
    /**
     * 分页查询
     */
    Page<UserEntity> findByNameLike(String name,Pageable pageable);

    
    /******************** 2、支持HQL语句进行操作接口示例 *********************/
    
    /**
     * HQL语句查询<br>
     */
    @Query("select u from UserEntity u where u.name = ?1 and u.age = ?2")
    List<UserEntity> findByHql(String user, Integer age);
	
    /**
     * HQL语句删除
     */
    @Query(value = "delete from UserEntity u where u.id=?1 ")
    @Modifying
    @Transactional
    public void deleteByHql(Integer id);
 
 
    /**
     * HQL修改
     */
    @Transactional
    @Query(value = "update UserEntity u set u.name=?1 where u.id=?2 ")
    @Modifying
    public void updateByHql(String name,int id);
 
    
    /******************** 3、支持原生SQL语句进行操作接口示例 *********************/

    /**
     * 原生SQL进行查询<br>
     */
    @Query(value = "select u.* from  user u where u.name = ?1 and u.age = ?2", nativeQuery = true)
    public List<UserEntity> findBySql(String name, Integer age);
    
    /**
     * 原生的SQL删除
     */
    @Transactional
    @Query(value = "delete from user where id=?1", nativeQuery = true)
    @Modifying
    public void deleteBySql(int id);
 
 
    /**
     * 原生的SQL修改
     */
    @Query(value = "update user set name=?1 where id=?2", nativeQuery = true)
    @Modifying
    @Transactional
    public void updateBySql(String name,int id);
 
    /**
     * 原生的SQL插入
     */
    @Query(value = "insert into user(name,age) value(?1,?2)", nativeQuery = true)
    @Modifying
    @Transactional
    public void insertBySql(String name,int age);

}

UserController2.java

package com.ldy.bootv2.demo.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ldy.bootv2.demo.dao.UserDao;
import com.ldy.bootv2.demo.entity.UserEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;

@Api(tags = "用户信息管理接口-v2-API")
@RestController
@RequestMapping("/user")
public class UserController2 {

	private static Logger logger = LoggerFactory.getLogger(UserController2.class);

	@Autowired
	UserDao userDao;

	@GetMapping("/findByNameLike")
	public List<UserEntity> findByNameLike(@RequestParam(value = "name") String name) {
	    logger.info("您调用了findByNameLike接口");
	    return userDao.findByNameLike("%" + name + "%");
	}

	@GetMapping("/findByAgeBetween")
	public List<UserEntity> findByAgeBetween(@RequestParam int min, @RequestParam int max) {
	    logger.info("您调用了findByNameLike接口");
	    return userDao.findByAgeBetween(min, max);
	}

	@SuppressWarnings("deprecation")
	@GetMapping("/findPage")
	public Page<UserEntity> findPage(
	    @RequestParam(value = "name") String name,
	    @RequestParam(value = "page", defaultValue = "0") Integer page,
	    @RequestParam(value = "size", defaultValue = "10") Integer size) {
	    logger.info("您调用了findPage接口");
	    Sort sort = new Sort(Sort.Direction.DESC, "id");
	    Pageable pageable = new PageRequest(page, size, sort);
	    Page<UserEntity> pages = userDao.findByNameLike("%" + name + "%", pageable);

	    return pages;
	}
	
	@GetMapping("/findByHql")
	public List<UserEntity> findByHql(
	    @RequestParam(value = "name") String name,
	    @RequestParam(value = "age") Integer age) {
	    logger.info("您调用了findByHql接口");
	    return userDao.findByHql(name,age);
	}
	
	@DeleteMapping("/deleteByHql/{id}")
	public String deleteByHql(@ApiParam(value = "用户id", required = true) @PathVariable("id") Integer id) {
	    logger.info("您调用了deleteBySql接口");
	    try {
	        userDao.deleteByHql(id);
	    } catch (Exception e) {
		logger.error("失败,原因:" + e.getMessage());
	        return "error";
	    }
	    return "success";
	}
	
	@GetMapping("/findBySql")
	public List<UserEntity> findBySql(
	    @RequestParam(value = "name") String name,
	    @RequestParam(value = "age") Integer age) {
	    logger.info("您调用了findBySql接口");
	    return userDao.findBySql(name,age);
	}

	@DeleteMapping("/deleteBySql/{id}")
	public String deleteBySql(@ApiParam(value = "用户id", required = true) @PathVariable("id") Integer id) {
	    logger.info("您调用了deleteBySql接口");
	    try {
		userDao.deleteBySql(id);
	    } catch (Exception e) {
		logger.error("失败,原因:" + e.getMessage());
		return "error";
	    }
	    return "success";
	}
	
	@GetMapping("/insertBySql")
	public String insertBySql(
	    @RequestParam(value = "name") String name,
	    @RequestParam(value = "age", defaultValue = "0") Integer age) {
	    logger.info("您调用了insertBySql接口");
	    try {
		userDao.insertBySql(name, age);
	    } catch (Exception e) {
		logger.error("失败,原因:" + e.getMessage());
		return "error";
	    }
	    return "success";
	}

}

6、运行项目,打开swagger页面,测试接口正常,swagger的集成请查看:https://blog.csdn.net/LDY1016/article/details/83415640

源码下载地址:https://pan.baidu.com/s/1Z771VDiuabDBJJV445xLeA#list/path=%2Fspring%20boot%202.x%20%E4%BB%A3%E7%A0%81

没有更多推荐了,返回首页