создал в базе всегда значение null, и версия не работает должным образом. - PullRequest
0 голосов
/ 08 февраля 2020

Я пытаюсь реализовать одну сущность, чтобы увидеть, как работает Аудит весной. У меня возникли проблемы с буксировкой:

Первая проблема заключается в том, что поле «create_by» всегда имеет значение null в базе данных, хотя я создал компонент AuditAware и установил его себе.

Второй проблема заключается в том, что всякий раз, когда я хочу вставить что-то в таблицу стран, это заставляет меня указывать номер версии. Это не то поведение, которое я хочу, так как я ожидаю, что версия будет подхвачена самой пружиной

Я ценю, если кто-то может помочь мне решить эти две проблемы.

AbstractMethodEntity выглядит следующим образом:

package com.xx.xxx.hotel;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.time.LocalDateTime;

@MappedSuperclass
@EntityListeners({ AuditingEntityListener.class })
public abstract class AbstractModelEntity<U> {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @Column(name = "created_by")
  @CreatedBy
  private U CreatedBy;

  @Column(name = "create_date")
  @CreatedDate
  private LocalDateTime createdDate;

  @Version
  private long version;

  @Column(name = "modified_by")
  @LastModifiedBy
  private U lastModifiedBy;

  @Column(name = "modified_date")
  @LastModifiedDate
  private LocalDateTime lastModifiedDate;

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public long getVersion() {
    return version;
  }

  public void setVersion(long version) {
    this.version = version;
  }

  public U getCreatedBy() {
    return CreatedBy;
  }

  public void setCreatedBy(U createdBy) {
    CreatedBy = createdBy;
  }

  public LocalDateTime getCreatedDate() {
    return createdDate;
  }

  public void setCreatedDate(LocalDateTime createdDate) {
    this.createdDate = createdDate;
  }

  public U getLastModifiedBy() {
    return lastModifiedBy;
  }

  public void setLastModifiedBy(U lastModifiedBy) {
    this.lastModifiedBy = lastModifiedBy;
  }

  public LocalDateTime getLastModifiedDate() {
    return lastModifiedDate;
  }

  public void setLastModifiedDate(LocalDateTime lastModifiedDate) {
    this.lastModifiedDate = lastModifiedDate;
  }
}

Сущность Country:

package com.xx.xxx.hotel.service.country;

import com.miraftabi.hossein.hotel.AbstractModelEntity;
import org.hibernate.envers.AuditOverride;
import org.hibernate.envers.Audited;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Audited
@AuditOverride(forClass = AbstractModelEntity.class, isAudited = true)
@Table(name = "country")
public class CountryEntity extends AbstractModelEntity<String> {

  @Column(name = "name", nullable = false)
  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

Файл AuditAwareImpl:

package com.xx.xxx.hotel.service;

import org.springframework.data.domain.AuditorAware;

import java.util.Optional;

public class AuditorAwareImpl implements AuditorAware<String> {
  @Override
  public Optional<String> getCurrentAuditor() {
    return Optional.of("Hossein");
  }
}

Файл AuditConfiguraiton:

package com.xx.xxx.hotel.config;

import com.xx.xxx.hotel.service.AuditorAwareImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class AuditConfiguration {

  @Bean
  public AuditorAware<String> auditorAware() {
    return new AuditorAwareImpl();
  }
}

Файл конфигурации репозитория:

package com.xx.xxx.hotel.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.envers.repository.support.EnversRevisionRepositoryFactoryBean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@Configuration
@EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
public class RepositoryConfiguration {
}

CountryRevisionRepository file:

package com.xx.xxx.hotel.service.country;

import org.springframework.data.repository.history.RevisionRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CountryRevisionRepository  extends RevisionRepository<CountryEntity, Long, Integer> {
}

Application.properties:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/hotel
spring.datasource.username=${DATABASE_USERNAME}
spring.datasource.password=${DATABASE_PASSWORD}

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

spring.jpa.open-in-view=false

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
...