1. 程式人生 > >十四、spring boot 2.x 整合 jpa 進階

十四、spring boot 2.x 整合 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";
	}

}