关于java:springbootroute九整合JPA操作数据库

23次阅读

共计 2820 个字符,预计需要花费 8 分钟才能阅读完成。

枯燥的增删改查让越来越多的程序员感到乏味,这时候就呈现了很多优良的框架,实现了对增删改查操作的封装,只须要简略配置,无需书写任何 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 框架。

此是 spring-boot-route 系列的第九篇文章,这个系列的文章都比较简单,次要目标就是为了帮忙首次接触 Spring Boot 的同学有一个零碎的意识。本文已收录至我的 github,欢送各位小伙伴star

github:https://github.com/binzh303/s…

点关注、不迷路

如果感觉文章不错,欢送 关注 点赞 珍藏,你们的反对是我创作的能源,感激大家。

如果文章写的有问题,请不要悭吝,欢送留言指出,我会及时核查批改。

如果你还想更加深刻的理解我,能够微信搜寻「Java 旅途」进行关注。回复「1024」即可取得学习视频及精美电子书。每天 7:30 准时推送技术文章,让你的下班路不在孤单,而且每月还有送书流动,助你晋升硬实力!

正文完
 0