在不使用spring.jpa.hibernate.ddl-auto的情况下,可以使用Spring Hibernate自动创建审计表的方法如下:
import org.springframework.data.jpa.domain.AbstractAuditable;
import javax.persistence.Entity;
@Entity
public class AuditEntity extends AbstractAuditable<User, Long> {
// 可以添加额外的字段
}
spring.data.jpa.repositories.enabled=false
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
@Component
public class AuditTableCreator implements ApplicationRunner {
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional
public void run(ApplicationArguments args) {
entityManager.createNativeQuery("CREATE TABLE IF NOT EXISTS audit_entity (id BIGINT PRIMARY KEY, created_date DATETIME, created_by VARCHAR(255), last_modified_date DATETIME, last_modified_by VARCHAR(255))").executeUpdate();
}
}
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
@Entity
@EnableJpaAuditing
@EntityListeners(AuditingEntityListener.class)
public class YourEntity {
// 实体类的定义
}
这样,当应用启动时,会自动创建审计表,并在需要审计的实体类中记录创建时间、创建人、修改时间、修改人等信息。
推荐的腾讯云相关产品:腾讯云数据库TencentDB、腾讯云容器服务TKE、腾讯云函数计算SCF。
腾讯云数据库TencentDB:https://cloud.tencent.com/product/cdb
腾讯云容器服务TKE:https://cloud.tencent.com/product/tke
腾讯云函数计算SCF:https://cloud.tencent.com/product/scf
领取专属 10元无门槛券
手把手带您无忧上云