java - 跳过特定表的创建 [Spring] [Hibernate]

标签 java spring hibernate spring-security spring-jdbc

我正在创建一些简单的 spring 项目(spring security),配置文件确定一些简单的值,如表名等。我在那里定义了一个 boolean 字段 REQUIRED_ACTIVATION,用于确定新用户是否必须使用发送的激活链接激活他的帐户通过邮件的示例。

public static final boolean REQUIRED_ACTIVATION = true;

如果我将 REQUIRED_ACTIVATION 值设置为 false,则用户在注册后立即处于 Activity 状态。我已经定义了包含激活链接数据的实体:

@Entity
@Table(name = 'user_activation_link')
public class UserActivationLink {
   [...]
}

当 REQUIRED_ACTIVATION 设置为 false 时,我不会在任何地方使用此类,而是在数据库中创建表。是否有任何解决方案来确定是否将根据 REQUIRED_ACTIVATION 的值创建表?

最佳答案

你需要做类似 this 的事情排除您不想在数据库中创建的表。

  • Implement the SchemaFilterProvider and the SchemaFilter interfaces
  • In the SchemaFilter implementation, add an if condition to includeTable so that it returns false for the table that you don’t want to create
  • Add hibernate.properties to the classpath and define hibernate.hbm2ddl.schema_filter_provider to point to the SchemaFilterProvider implementation
hibernate.hbm2ddl.schema_filter_provider=com.your.package.Provider

还有:

package com.your.package;

import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.mapping.Table;
import org.hibernate.tool.schema.spi.SchemaFilter;
import org.hibernate.tool.schema.spi.SchemaFilterProvider;

public class Provider implements SchemaFilterProvider {

    @Override
    public SchemaFilter getCreateFilter() {
        return MySchemaFilter.INSTANCE;
    }

    @Override
    public SchemaFilter getDropFilter() {
        return MySchemaFilter.INSTANCE;
    }

    @Override
    public SchemaFilter getMigrateFilter() {
        return MySchemaFilter.INSTANCE;
    }

    @Override
    public SchemaFilter getValidateFilter() {
        return MySchemaFilter.INSTANCE;
    }
}

class MySchemaFilter implements SchemaFilter {

    public static final MySchemaFilter INSTANCE = new MySchemaFilter();

    @Override
    public boolean includeNamespace(Namespace namespace) {
        return true;
    }

    @Override
    public boolean includeTable(Table table) {
        if (//REQUIRED_ACTIVATION==true && table.getName() is the table you want to exclude){
            return false;
        }
        return true;
    }

    @Override
    public boolean includeSequence(Sequence sequence) {
        return true;
    }
}

关于java - 跳过特定表的创建 [Spring] [Hibernate],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63649640/

相关文章:

java - 如何将 URI 中的尾随字符从 # 更改为/in <rdf :RDF xmlns =""> - owl api

java - Spring 表单中可变数量的字段

java - 在 AJax 中提交 Spring 表单始终为 null

java - Oracle Hibernate 映射 - NUMBER(4,0)

Hibernate uuid 生成出现 'data too long' 错误

hibernate - 如何避免与 DbUnit 插入的 ID 和 Hibernate 插入的实体发生冲突

java - 使用 JPA 连接刷新

java - 将文件系统从路径列表保存到 SQL 数据库中

java - java中的模糊逻辑

java - 错误 HTTP 状态 403 - 在请求参数 'null' 或 header '_csrf' 上发现无效的 CSRF token 'X-CSRF-TOKEN'