JPA实战之save

本文通过实例分析了JPA中save()方法的使用,揭示了其内部执行的SQL语句。在不同场景下,save()可能涉及select查询、insert插入或update更新操作。当启用show-sql配置,可以清晰看到这些过程。同时,文章探讨了事务注解(@Transactional)对save()行为的影响,即使无查询,事务环境下仍会先执行查询。

前言:之前一直都是直接使用JPA没有想过它内部封装的sql语言,然后看到了一篇文章 JPA踩坑系列之save方法,才发现这个框架并不好用。

验证save()的使用

pom文件

<?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.6.1</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>demo</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</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>

yml文件

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/springboot_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    driverClassName: com.mysql.cj.jdbc.Driver
    username: root
    password: root1234
  jpa:
    show-sql: true 
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate:
      use-new-id-generator-mappings: false
    properties:
      hibernate.format_sql: true

show-sql: true 可以展示调用过程中的sql语句。

create table user
(
    user_id   varchar(20) null,
    enabled   tinyint(1)  not null,
    id        int auto_increment
        primary key,
    role_code varchar(50) not null,
    name      varchar(10) null,
    constraint dealer_id_role_code_idx
        unique (user_id, role_code)
)
    charset = utf8;

项目结构
在这里插入图片描述
user文件

package com.example.demo.entity;

import lombok.*;

import javax.persistence.*;
import java.io.Serializable;

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Getter
@Setter
@Table(name = "user")
public class User implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private int id;

    @Column(name = "user_id", length = 50, nullable = false)
    private String userId;

    @Column(name = "enabled", length = 1, nullable = false)
    private Boolean enabled;

    @Column(name = "role_code", length = 50, nullable = false)
    private String roleCode;

    private String name;

}

UserRepository文件

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
@ComponentScan
public interface UserRepository extends JpaRepository<User, Integer> {

    User findByUserIdAndRoleCode(String userID, String roleCode);
}

UserService文件

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public int addUser(String userId) {
        User user = User.builder()
                .id(45747)
                .userId(userId)
                .enabled(false)
                .roleCode("Sup")
                .name("haha").build();
        return userRepository.save(user).getId();
    }
}

调用的mysql语句

Hibernate: 
    select
        user0_.id as id1_0_0_,
        user0_.enabled as enabled2_0_0_,
        user0_.name as name3_0_0_,
        user0_.role_code as role_cod4_0_0_,
        user0_.user_id as user_id5_0_0_ 
    from
        user user0_ 
    where
        user0_.id=?
Hibernate: 
    insert 
    into
        user
        (enabled, name, role_code, user_id) 
    values
        (?, ?, ?, ?)

因为创建user对象的时候涉及到了主键id,所以在save之前会进行一次select操作,以主键id为依据。

UserService文件

 public int addUser(String userId) {
        User user = User.builder()
                .userId(userId)
                .enabled(false)
                .roleCode("Sup")
                .name("haha").build();
        return userRepository.save(user).getId();
    }

调用的mysql语句

Hibernate: 
    insert 
    into
        user
        (enabled, name, role_code, user_id) 
    values
        (?, ?, ?, ?)

当没有涉及主键的操作后,会直接调用insert操作。

UserService文件

 public int addUser(String userId) {
    User user = userRepository.findByUserIdAndRoleCode(userId,"Sup");
        user.setEnabled(true);
        return userRepository.save(user).getId();
    }

调用的mysql语句

Hibernate: 
    select
        user0_.id as id1_0_,
        user0_.enabled as enabled2_0_,
        user0_.name as name3_0_,
        user0_.role_code as role_cod4_0_,
        user0_.user_id as user_id5_0_ 
    from
        user user0_ 
    where
        user0_.user_id=? 
        and user0_.role_code=?
Hibernate: 
    select
        user0_.id as id1_0_0_,
        user0_.enabled as enabled2_0_0_,
        user0_.name as name3_0_0_,
        user0_.role_code as role_cod4_0_0_,
        user0_.user_id as user_id5_0_0_ 
    from
        user user0_ 
    where
        user0_.id=?
Hibernate: 
    update
        user 
    set
        enabled=?,
        name=?,
        role_code=?,
        user_id=? 
    where
        id=?

会按照查询条件先查一遍,然后再根据主键进行查找,发现值发生变化后,再进行update操作,没有变化不再进行操作,如下所示。
UserService文件

 public int addUser(String userId) {
    User user = userRepository.findByUserIdAndRoleCode(userId,"Sup");
        user.setEnabled(false);
        return userRepository.save(user).getId();
    }

调用的mysql语句

Hibernate: 
    select
        user0_.id as id1_0_,
        user0_.enabled as enabled2_0_,
        user0_.name as name3_0_,
        user0_.role_code as role_cod4_0_,
        user0_.user_id as user_id5_0_ 
    from
        user user0_ 
    where
        user0_.user_id=? 
        and user0_.role_code=?
Hibernate: 
    select
        user0_.id as id1_0_0_,
        user0_.enabled as enabled2_0_0_,
        user0_.name as name3_0_0_,
        user0_.role_code as role_cod4_0_0_,
        user0_.user_id as user_id5_0_0_ 
    from
        user user0_ 
    where
        user0_.id=?

当给方法加上事务的注解(@Transactional)后,
UserService文件

@Transactional
 public int addUser(String userId) {
    User user = userRepository.findByUserIdAndRoleCode(userId,"Sup");
        user.setEnabled(false);
        return userRepository.save(user).getId();
    }

调用的mysql如下:

Hibernate: 
    select
        user0_.id as id1_0_,
        user0_.enabled as enabled2_0_,
        user0_.name as name3_0_,
        user0_.role_code as role_cod4_0_,
        user0_.user_id as user_id5_0_ 
    from
        user user0_ 
    where
        user0_.user_id=? 
        and user0_.role_code=?

但是当加上事物注解@Transactional,save前没有查询的话还是会先调用select语句
UserService文件

@Transactional
    public int addUser(String userId) {
    User user = User.builder()
                .id(123)
                .userId(userId)
                .enabled(false)
                .roleCode("Sup")
                .name("haha").build();
    return userRepository.save(user).getId();
    }

调用的mysql如下:

Hibernate: 
select
        user0_.id as id1_0_0_,
        user0_.enabled as enabled2_0_0_,
        user0_.name as name3_0_0_,
        user0_.role_code as role_cod4_0_0_,
        user0_.user_id as user_id5_0_0_ 
    from
        user user0_ 
    where
        user0_.id=?
Hibernate: 
    insert 
    into
        user
        (enabled, name, role_code, user_id) 
    values
        (?, ?, ?, ?)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值