spring-boot-route(九)整合JPA操作数据库

单调的增删改查让越来越多的程序员感到乏味,这时候就出现了很多优秀的框架,完成了对增删改查操作的封装,只需要简单配置,无需书写任何sql,就可以完成增删改查。这里比较推荐的是Spring Data Jpa。

Spring Data JPA是Spring Data家族的一部分,可以轻松实现基于JPA的存储库。 此模块处理对基于JPA的数据访问层的增强支持。 它使构建使用数据访问技术的Spring驱动应用程序变得更加容易。

我们继续使用前两章用的数据库结构来进行演示。

一 引入mysql和spring-data-jpa依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

二 创建实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Student implements Serializable {

    private static final long serialVersionUID = 6712540741269055064L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer studentId;
    private Integer age;
    private String name;
    private Integer sex;
    private Date createTime;
    private Integer status;
}

@GeneratedValue是主键生成策略,Jpa自带的几种主键生成策略如下:

  • TABLE: 使用一个特定的数据库表格来保存主键

  • SEQUENCE: 根据底层数据库的序列来生成主键,条件是数据库支持序列。这个值要与generator一起使用,generator 指定生成主键使用的生成器(可能是orcale中自己编写的序列)

  • IDENTITY: 主键由数据库自动生成(主要是支持自动增长的数据库,如mysql)

  • AUTO: 主键由程序控制,也是GenerationType的默认值

主键生成策略扩展

自定义主键生成器:

public class MyGenerator implements IdentifierGenerator {
    
    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        return getId();
    }
    
    public static long getId(){
        return System.currentTimeMillis();
    }
}

然后在实体类做一下配置:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Student implements Serializable {

    private static final long serialVersionUID = 6712540741269055064L;

    @Id
    @GenericGenerator(name="idGenerator",strategy = "com.javatrip.springdatajpa.entity.MyGenerator")
    @GeneratedValue(generator = "idGenerator")
    private Integer studentId;
    private Integer age;
    private String name;
    private Integer sex;
    private Date createTime;
    private Integer status;
}

三 创建dao接口

dao层接口实现JpaRepository,泛型选择pojo和其主键类型,就会自动实现简单的CRUD等接口,无需手动开发,就能快速进行调用。

public interface StudentRepository extends JpaRepository<Student,Integer> {

    /**
     * 根据年龄,名字模糊查询
     * @return
     */
    Student findByNameLikeAndAge(String name,int age);
}

Jpa除了实现CRUD方法,还支持字段名模糊查询等各种不用手写sql的操作。

四 测试类测试CRUD

@SpringBootTest
class SpringDataJpaApplicationTests {

    @Autowired
    StudentRepository repository;
    @Test
    void contextLoads() {
        // 查询所有实体
        List<Student> all = repository.findAll();
        // 根据id查询实体类
        Optional<Student> byId = repository.findById(100);
        // 根据id删除数据
        repository.deleteById(100);
        // 插入一条数据
        // 如果数据库存在该实体的主键,则更新,否则插入
        Student student = new Student();
        student.setAge(18);
        student.setName("Java旅途");
        repository.save(student);

        repository.findByNameLikeAndAge("Java",18);
    }
}

spring-data-jpa在外国程序员界非常普遍。相比其他两种方式,它不需要写sql就可以完成非常完善的数据操作,我也是比较推荐使用它作为orm框架。


本文示例代码已上传至github,点个star支持一下!

Spring Boot系列教程目录

spring-boot-route(一)Controller接收参数的几种方式

spring-boot-route(二)读取配置文件的几种方式

spring-boot-route(三)实现多文件上传

spring-boot-route(四)全局异常处理

spring-boot-route(五)整合swagger生成接口文档

spring-boot-route(六)整合JApiDocs生成接口文档

spring-boot-route(七)整合jdbcTemplate操作数据库

spring-boot-route(八)整合mybatis操作数据库

spring-boot-route(九)整合JPA操作数据库

spring-boot-route(十)多数据源切换

spring-boot-route(十一)数据库配置信息加密

spring-boot-route(十二)整合redis做为缓存

spring-boot-route(十三)整合RabbitMQ

spring-boot-route(十四)整合Kafka

spring-boot-route(十五)整合RocketMQ

spring-boot-route(十六)使用logback生产日志文件

spring-boot-route(十七)使用aop记录操作日志

spring-boot-route(十八)spring-boot-adtuator监控应用

spring-boot-route(十九)spring-boot-admin监控服务

spring-boot-route(二十)Spring Task实现简单定时任务

spring-boot-route(二十一)quartz实现动态定时任务

spring-boot-route(二十二)实现邮件发送功能

spring-boot-route(二十三)开发微信公众号

spring-boot-route(二十四)分布式session的一致性处理

spring-boot-route(二十五)两行代码实现国际化

spring-boot-route(二十六)整合webSocket

这个系列的文章都是工作中频繁用到的知识,学完这个系列,应付日常开发绰绰有余。如果还想了解其他内容,扫面下方二维码告诉我,我会进一步完善这个系列的文章!

posted @ 2020-10-08 14:09  Java旅途  阅读(546)  评论(0编辑  收藏  举报