商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > 使用spring-data-jpa实现简单的两表联查实践

使用spring-data-jpa实现简单的两表联查实践

  发布于2026-06-02 阅读(0)

扫一扫,手机访问

spring-data-jpa实现简单的两表联查

刚接触Spring Data JPA的时候,第一感觉就是——这东西让基本的增删改查变得非常简洁。不用再写一堆冗长的SQL和DAO实现,只需要定义好接口,很多操作就自动搞定了。下面整理了一些基础操作,希望能给刚入门的朋友一些参考。

spring家族

Spring Boot
spring Cloud
Spring framework
Spring-data
	Spring data-jpa(简单的增删改查)

jpa配置

JPA的底层实际上就是Hibernate,这一点需要先了解。在做多表联查的时候,会用到一对多、多对一这些关系映射。

如果项目是一个Spring Boot Web程序,记得一定要配置好数据源,不然启动会报错。

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/studentdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBeha vior=CONVERT_TO_NULL
  jpa:
    database: mysql
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    show-sql: true
  profiles:
    active: local

接下来是实体类,利用JPA可以快速生成数据库表。

@Data
@Entity
public class Student {
    @Id
    private Long stuid;
    private String name;
    private String sex;
    @ManyToOne
    private Grade grade;
}

Id列的注解

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
/*Id表示主键  主键有生成策略*/
/*GenerationType.IDENTITY唯一列还自动增长*/
/*GenerationType.AUTO自动增长*/
/*Oracle中是没有自动增长的 设置GenerationType.SEQUENCE  使用序列进行增长*/
/*GeneratedValue 自动增长生成的value值*/

普通列注解

@Column

启动项目后,数据库表会自动创建成功。

使用spring-data-jpa实现简单的两表联查实践

接着是数据访问层的接口,直接继承JpaRepository就能获得大量通用方法。

public interface StudentMapper extends JpaRepository, JpaSpecificationExecutor {
}

Service层的实现也很清爽,逻辑直接调用Mapper即可。

@Service
public class StudentServiceImpl {

    @Autowired
    private StudentMapper studentMapper;

    public Page students(Integer pageNum, Integer size){
        if(pageNum==null||pageNum<0){
            pageNum=0;
        }
        if (size==null){
            size=2;
        }
        return studentMapper.findAll(PageRequest.of(pageNum,size));
    }

    public void del(Long id){
        try {
            studentMapper.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Student getByid(Long id){
        Optional byId = studentMapper.findById(id);
        return byId.get();
    }

    public Student add(Student student){
        return studentMapper.sa ve(student);
    }

    public Student upd(Student student){
        return studentMapper.sa ve(student);
    }
}

因为实体类中的Id我没有配置自增策略,所以需要在代码里手动生成ID,并且保证全局唯一。为此准备了一个雪花算法的工具类。

public class IdWorker {
    // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
    private final static long twepoch = 1288834974657L;
    // 机器标识位数
    private final static long workerIdBits = 5L;
    // 数据中心标识位数
    private final static long datacenterIdBits = 5L;
    // 机器ID最大值
    private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
    // 数据中心ID最大值
    private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    // 毫秒内自增位
    private final static long sequenceBits = 12L;
    // 机器ID偏左移12位
    private final static long workerIdShift = sequenceBits;
    // 数据中心ID左移17位
    private final static long datacenterIdShift = sequenceBits + workerIdBits;
    // 时间毫秒左移22位
    private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
    /* 上次生产id时间戳 */
    private static long lastTimestamp = -1L;
    // 0,并发控制
    private long sequence = 0L;

    private final long workerId;
    // 数据标识id部分
    private final long datacenterId;

    public IdWorker(){
        this.datacenterId = getDatacenterId(maxDatacenterId);
        this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    }
    /**
     * @param workerId
     *            工作机器ID
     * @param datacenterId
     *            序列号
     */
    public IdWorker(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }
    /**
     * 获取下一个ID
     *
     * @return
     */
    public synchronized long nextId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            // 当前毫秒内,则+1
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                // 当前毫秒内计数满了,则等待下一秒
                sequence = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        // ID偏移组合生成最终的ID,并返回ID
        long nextId = ((timestamp - twepoch) << timestampLeftShift)
                | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift) | sequence;

        return nextId;
    }

    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * 

* 获取 maxWorkerId *

*/ protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) { StringBuffer mpid = new StringBuffer(); mpid.append(datacenterId); String name = ManagementFactory.getRuntimeMXBean().getName(); if (!name.isEmpty()) { /* * GET jvmPid */ mpid.append(name.split("@")[0]); } /* * MAC + PID 的 hashcode 获取16个低位 */ return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1); } /** *

* 数据标识id部分 *

*/ protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; }

在启动类中将工具类注册为Bean。

@SpringBootApplication
public class SpringDataJpa01Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringDataJpa01Application.class, args);
    }

    @Bean
    public IdWorker sb(){
        return new IdWorker();
    }
}

调用新增方法时,效果如下:

使用spring-data-jpa实现简单的两表联查实践

最后是Controller层的实现,也一并贴出来。

@Controller
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private IdWorker idWorker;

    @GetMapping("/students")
    public String findAll(Integer pageNum, Integer size, Model model) {
        Page students = studentService.students(pageNum, size);
        model.addAttribute("students", students);
        return "index";
    }

    @DeleteMapping("/student/{id}")
    public String del(@PathVariable("id") Long id) {
        studentService.del(id);
        return "redirect:/students";
    }

    @GetMapping("/student")
    public String edit(Long id, Model model) {
        model.addAttribute("grades", gradeMapper.findAll());
        if (id != null) {
            model.addAttribute("students", studentService.getByid(id));
        }
        return "edit";
    }

    @PostMapping("/student")
    public String add(Student student) {
        student.setStuid(idWorker.nextId());
        studentService.add(student);
        return "redirect:/students";
    }

    @PutMapping("/student")
    public String upd(Student student) {
        studentService.upd(student);
        return "redirect:/students";
    }
}

对应的页面模板——index.html(列表页)




    
    Title


添加
        name:
# 姓名 性别 年级 操作
# 姓名 性别 年级 修改
首页 上一页 下一页 下一页 尾页 共[[${students.totalPages}]]页,当前第[[${students.number}+1]]

以及添加/修改页面




    
    Title


name:
sex:
grade:

总结

以上这些就是Spring Data JPA做简单两表联查的基本流程,从配置数据源、建实体类、写DAO、Service到Controller和前端页面,整体下来代码量少了很多,特别适合快速开发后台管理系统。如果有其他更好的实践方式,也欢迎一起交流。

本文转载于:https://www.jb51.net/program/365022vo7.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注