spring boot中jpa使用
文章目录
一、简介
jpa(java persistence api)是java数据持久化的标准规范,常用实现为hibernate,这里介绍spring boot中jpa的使用。
二、开发步骤
在spring boot中jpa的开发步骤如下:
-
在application.yaml中添加配置,如下:
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8 username: root password: root driverClassName: com.mysql.jdbc.Driver
-
定义实体bean,使用注解@Entity修饰,使用注解@Table指定数据库表名。属性可使用@Column指定对应表字段特点,可使用注解@Id指定主键,使用@GeneratedValue指定主键生成方式;
-
定义实体对应的repository,继承JpaRepository类,泛型中指定实体类型和主键;
-
使用中直接调用前面定义的repository中方法或自定义方法即可。
三、示例
3.1 添加maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dragon.study</groupId>
<artifactId>spring_boot_jpa_mysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_boot_jpa_mysql</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.spring