首页 > 编程语言 > springdata jpa单表操作crud的实例代码详解
2021
01-12

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单表操作内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

编程技巧