什么是JPA
JPA(Java Persistence API),也称之为Java持久层API,简单来说就是基本上不需要写SQL,通过方法名就可以实现相应的数据库操作,并且也可以自动生成表结构,比如我们有个实体对象users,在通过JPA的save,就可以进行insert操作了,更加突出的地方是根据方法名就可以执行相应的操作,不需要手写SQL了,但是也仅仅是简单的SQL,复杂的SQL效果不是很理想了。
比如我们要通过Username来获取这个实体对象,就可以getUserEntitiesByUsername这样定义。
代码
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.7.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>top.zunmx</groupId>
<artifactId>jpa_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jpa_demo</name>
<description>jpa_demo</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
springboot配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
password: ******
url: jdbc:mysql://localhost:3306/jpa # 需要提前创建好数据库
username: root
jpa:
hibernate:
ddl-auto: update # ddl策略
show-sql: true # 控制台输出sql
ddl-auto 参数
- create 启动的时候删除表,然后创建,退出的时候不删除表,
启动时执行drop table if exists ··· - create-drop 启动时删除表,然后创建,退出时删除数据表 如果表不存在报错
启动和结束时执行drop table if exists ··· - update 如果启动时表格式不一致则更新表,原有数据保留
- validate 项目启动表结构进行校验,如果与实体对象不一致则报错
启动类
package top.zunmx.jpa_demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JpaDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JpaDemoApplication.class, args);
}
}
实体类
package top.zunmx.jpa_demo.entity;
import lombok.Data;
import javax.persistence.*;
@Data
@Table(name = "users") // 表名
@Entity
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //MySQL 自增字段
private int id;
private String username;
private String password;
}
控制器
package top.zunmx.jpa_demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.zunmx.jpa_demo.entity.UserEntity;
import top.zunmx.jpa_demo.jpa.userRepository;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Optional;
@RestController
public class base {
@Resource
userRepository repository;
@GetMapping("/insert")
public UserEntity insert(String username, String password) {
UserEntity UserEntity = new UserEntity();
UserEntity.setUsername(username);
UserEntity.setPassword(password);
repository.save(UserEntity);
return UserEntity;
}
@GetMapping("/getbyid")
public UserEntity getbyid(int id) {
Optional<UserEntity> byId = repository.findById(id);
UserEntity UserEntity = byId.get();
return UserEntity;
}
@GetMapping("/update")
public UserEntity getbyid(int id, String username, String password) {
repository.updateAllById(id,password,username);
return repository.findById(id).get();
}
@GetMapping("delete")
public int delete(int id){
boolean b = repository.existsById(id);
if(b) {
repository.deleteById(id);
return 1;
}else{
return 0;
}
}
@GetMapping("getUsersByName")
public ArrayList<UserEntity> getByName(String name){
UserEntity userEntity = new UserEntity();
userEntity.setUsername(name);
ArrayList<UserEntity> userEntitiesByUsername = repository.getUserEntitiesByUsername(name);
return userEntitiesByUsername;
}
}
jpa映射
package top.zunmx.jpa_demo.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import top.zunmx.jpa_demo.entity.UserEntity;
import javax.transaction.Transactional;
import java.util.ArrayList;
@Repository
public interface userRepository extends JpaRepository<UserEntity, Integer> {
@Transactional //开启事务
@Modifying
@Query("update UserEntity set password=?2,username=?3 where id=?1")
/*自定义sql,?相当于mybatis中的#,预编译,当实体和表名不一致的情况下,UserEntity要和实体对象一致。也就是HQL语句中表名应该是ORM映射的类名*/
void updateAllById(int id,String password,String username);
ArrayList<UserEntity> getUserEntitiesByUsername(String username);
}
测试结果
http://127.0.0.1:8080/insert?username=12345&password=1234
{"id":11,"username":"12345","password":"1234"}
http://127.0.0.1:8080/getbyid?id=1
{"id":1,"username":"123","password":"1234"}
http://127.0.0.1:8080/update?id=1&username=aaa&password=aaa
{"id":1,"username":"aaa","password":"aaa"}
http://127.0.0.1:8080/delete?id=9
0
http://127.0.0.1:8080/getUsersByName?name=12345
[{"id":7,"username":"12345","password":"1234"},{"id":8,"username":"12345","password":"1234"},{"id":10,"username":"12345","password":"1234"},{"id":11,"username":"12345","password":"1234"}]
http://127.0.0.1:8080/getUsersByName?name=aaa
[{"id":1,"username":"aaa","password":"aaa"}]
日志
Hibernate: insert into users (password, username) values (?, ?)
Hibernate: select userentity0_.id as id1_0_0_, userentity0_.password as password2_0_0_, userentity0_.username as username3_0_0_ from users userentity0_ where userentity0_.id=?
Hibernate: update users set password=?, username=? where id=?
Hibernate: select userentity0_.id as id1_0_0_, userentity0_.password as password2_0_0_, userentity0_.username as username3_0_0_ from users userentity0_ where userentity0_.id=?
Hibernate: select count(*) as col_0_0_ from users userentity0_ where userentity0_.id=?
Hibernate: select userentity0_.id as id1_0_, userentity0_.password as password2_0_, userentity0_.username as username3_0_ from users userentity0_ where userentity0_.username=?

评论 0
还没有评论,来说点什么吧。