springdata jpa單表操作crud的實例代碼詳解

1. 項目搭建

使用boot整合,導入springdata jap, mysql 驅動,lombok,web。

1.1 配置

# boot add jpa, oh~ crud in single table

server:
 port: 8888
spring:
 # datasource
 datasource:
 username: root
 password: 123456
 driver-class-name: com.mysql.cj.jdbc.Driver
 url: jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai

 # jpa config
 jpa:
 hibernate:
  #配置創建表的相關操作
  ddl-auto: update
 #顯示sql
 show-sql: true

1.2 實體類

package top.bitqian.springdatajpa.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author echo lovely
 * @date 2021/1/10 16:06
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "programmer_info")
@Entity
public class ProgrammerInfo {
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Integer programmerId;

 @Column(name = "name", unique = true, nullable = false, length = 50)
 private String name;

 /**
  * 0 male
  * 1 female
  */
 private Integer gender;

 private Date personBirth;

 @Transient // 生成表的時候忽略money字段
 private BigDecimal money;
}

1.3 繼承JpaRepository接口

package top.bitqian.springdatajpa.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import top.bitqian.springdatajpa.entity.ProgrammerInfo;

/**
 * @author echo lovely
 * @date 2021/1/10 16:13
 */

public interface ProgrammerRepository extends JpaRepository<ProgrammerInfo, Integer> {

	// TODO: todo sth...
	
}

2. 批量新增

業務類

package top.bitqian.springdatajpa.service.impl;

import org.springframework.stereotype.Service;
import top.bitqian.springdatajpa.entity.ProgrammerInfo;
import top.bitqian.springdatajpa.repository.ProgrammerRepository;
import top.bitqian.springdatajpa.service.ProgrammerInfoService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author echo lovely
 * @date 2021/1/10 16:15
 */

@Service
public class ProgrammerInfoServiceImpl implements ProgrammerInfoService {

 @Resource
 private ProgrammerRepository programmerRepository;

 @Override
 public void saveBatch(List<ProgrammerInfo> programmerInfos) {

  programmerRepository.
    saveAll(programmerInfos).
    forEach(r -> System.out.println("批量新增完成 =>" + r));

 }
}

測試

package top.bitqian.springdatajpa;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import top.bitqian.springdatajpa.entity.ProgrammerInfo;
import top.bitqian.springdatajpa.service.ProgrammerInfoService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SpringBootTest
class SpringdataJpaApplicationTests {

 @Resource
 private ProgrammerInfoService programmerInfoService;

 @Test
 void contextLoads() {

  List<ProgrammerInfo> list = new ArrayList<>();

  Date date = new Date();

  list.add(new ProgrammerInfo(null, "小千", 0, date, null));
  list.add(new ProgrammerInfo(null, "小小", 1, date, null));
  list.add(new ProgrammerInfo(null, "二哈", 0, date, null));

  programmerInfoService.saveBatch(list);

 }

}

3. 查詢

根據條件精確查詢, Example作為參數。

@Override
 public List<ProgrammerInfo> getProgrammerByInfo(ProgrammerInfo programmerInfo) {

  // 根據條件查詢集合
  Example<ProgrammerInfo> example = Example.of(programmerInfo);

  return programmerRepository.findAll(example);
 }
@Test
 void testGetProgrammerByInfo() {
		// 根據姓名查詢。
  ProgrammerInfo info = new ProgrammerInfo(null, "小小", null, null, null);
  programmerInfoService.getProgrammerByInfo(info).forEach(System.out::println);
 }

 

在這裡插入圖片描述

自定義hql語句查詢

// 1. query by hql
 @Query(value = "from ProgrammerInfo pi where pi.name like ?1")
 List<ProgrammerInfo> findProgrammerByName(String name);
@Test
 void testPrByName() {

  // 查詢名稱包含 '小'
  pr.findProgrammerByName("%小%").forEach(System.out::println);

 }

 

自定義sql語句查詢

 // 2. query by sql
 @Query(value = "select * from programmer_info where name like :#{#pi.name} and gender = :#{#pi.gender}", nativeQuery = true)
 List<ProgrammerInfo> findPrByPrInfo(@Param("pi") ProgrammerInfo programmerInfo);
 @Test
 void testPrByPr() {

  ProgrammerInfo info = new ProgrammerInfo(null, "%小%", 0, null, null);

  pr.findPrByPrInfo(info).forEach(System.out::println);
 }

4. 修改 by hql

sql也行,hql優先。

 // upd
 @Transactional
 @Modifying
 @Query(value = "update ProgrammerInfo p set p.name = :#{#pi.name}, p.personBirth = :#{#pi.personBirth} where p.programmerId = :#{#pi.programmerId}")
 void updPrById(@Param("pi") ProgrammerInfo programmerInfo);
 @Test
 void testPrUpd() {
  ProgrammerInfo info = new ProgrammerInfo(1, "小小可愛", 0, new Date(), null);
  pr.updPrById(info);

 }

5. 刪除 by hql

 // del
 @Transactional
 @Modifying
 @Query(value = "delete from ProgrammerInfo where programmerId = :#{#pi.programmerId}")
 void delPrById(@Param("pi") ProgrammerInfo programmerInfo);
 @Test
 void testPrDel() {
  ProgrammerInfo info = new ProgrammerInfo(1, null, 0, null, null);

  pr.delPrById(info);

 }

在這裡插入圖片描述


1. 修改操作得加上事務控制。
2. @Query 進行操作時,占位符使用註意套娃。不要套錯。

單表操作可以的,但是mybatisPlus 更easy.jpg.

到此這篇關於springdata jpa單表操作crud的文章就介紹到這瞭,更多相關springdata jpa單表操作內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: