spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
2.92k stars 1.39k forks source link

@Version column seems to cause JPA to delete subsequent inserts #3488

Closed agdt3 closed 1 month ago

agdt3 commented 1 month ago

Hi all,

Ran into a potential issue that's breaking a lot of my code, but not 100% sure if its a new issue. Basically, if you have a @Version column on a child or related entity, that entity will be rolled back if its in some way related to parent.

Example code:

Entities:

@ToString
@Getter
@Setter
@Entity
@Table(name = "Employee")
public class Employee {

    @Id
    private String id;

    @Column
    private String email;

    @Column
    private String userName;
    ...

    @Column
    @Version
    private Integer version;
}

...

@ToString
@Getter
@Setter
@Entity
@Table(name = "EmployeeLabourRateModifier")
public class EmployeeLabourRateModifier {

    @Id
    private String id;

    @Column
    private String employeeId;

    @Column
    private String labourRateModifierId;
    ...

    @Version
    @Column
    private Integer version;
}

Repositories:

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, String> {
}
...
@Repository
public interface EmployeeLabourRateModifierRepository extends CrudRepository<EmployeeLabourRateModifier, String> {
}

Service:

 @Override
    public Map<String, List<String>> createEmployee(List<CreateEmployeeRequest> createEmployeeRequests) {
        Map<String, List<String>> response = new HashMap<>();

        try {
            createEmployeeRequests.forEach(createEmployeeRequest -> {
                String employeeId = UUID.randomUUID().toString();

                Employee employee = new Employee();
                employee.setId(employeeId);
                employee.setUserName(createEmployeeRequest.getUserName());
                employee.setEmail(createEmployeeRequest.getEmail());
                Employee createdEmployee = employeeRepository.save(employee);

                List<EmployeeLabourRateModifier> employeeLabourRateModifiers = new ArrayList<>();
                createEmployeeRequest
                    .getLabourRateModifierIds()
                    .forEach(labourRateModifierId -> {
                        String employeeLabourRateModifierId = UUID.randomUUID().toString();
                        EmployeeLabourRateModifier employeeLabourRateModifier = new EmployeeLabourRateModifier();
                        employeeLabourRateModifier.setId(employeeLabourRateModifierId);
                        employeeLabourRateModifier.setEmployeeId(createdEmployee.getId());
                        employeeLabourRateModifier.setLabourRateModifierId(labourRateModifierId);

                        employeeLabourRateModifiers.add(employeeLabourRateModifier);
                    });
                Iterable<EmployeeLabourRateModifier> createdModifiers = this.employeeLabourRateModifierRepository.saveAll(employeeLabourRateModifiers);
                List<String> ids = new ArrayList<>();
                createdModifiers.forEach(createdModifier -> {
                    ids.add(createdModifier.getId());
                });

                response.put(createdEmployee.getId(), ids);
            });
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }
        return response;
    }

DB In the DB, the version column is defined as int, nullable=true, no default value.

The basic issue here is if you leave the @Version columns in, you get the following DB process (no errors thrown by spring data jpa):

Screenshot 2024-05-25 at 1 57 30 PM

If you remove the @Version columns, you get just normal inserts:

Screenshot 2024-05-25 at 1 59 15 PM

Things I have tried that did not work:

Things that did work:

pom.xml:

<?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 http://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>3.3.0</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.buildops</groupId>
    <artifactId>test-core</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>17</java.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.awspring.cloud</groupId>
                <artifactId>spring-cloud-aws-dependencies</artifactId>
                <version>3.1.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- REST but also any web application -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- RDS -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.33</version>
        </dependency>

        <!-- Healthchecks -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- Testing -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
            <optional>true</optional>
            <version>1.18.32</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

application.yml

spring:
  application:
    name: testapp
  cloud:
    aws:
      region:
        static: us-east-1
  datasource:
    url: ${RDS_URL}
    username: ${RDS_USERNAME}
    password: ${RDS_PASSWORD}
    driverClassName: com.mysql.cj.jdbc.Driver
  jpa:
    database-platform: org.hibernate.dialect.MySQLDialect
    properties:
      hibernate:
        order_inserts: true
        format_sql: true
        show_sql: ${DEBUG}
        use_sql_comments: ${DEBUG}
        generate_statistics: true
    hibernate:
      ddl-auto: validate
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
agdt3 commented 1 month ago

Addendum: simply having a version column, even without the annotation, triggers the same effect. e.g.

@Column
private Integer version;
mp911de commented 1 month ago

Any SQL interaction is subject to Hibernate, Spring Data merely uses EntityManager method calls to persist objects, any database interaction is handled by Hibernate.

agdt3 commented 1 month ago

@mp911de Apologies for misfiling.

Perhaps its related to this: https://hibernate.atlassian.net/browse/HHH-18175 https://github.com/hibernate/hibernate-orm/pull/8468