gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:26:02 27 4
gpt4 key购买 nike

我正在创建一些简单的 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’twant to create
  • Add hibernate.properties to the classpath and define hibernate.hbm2ddl.schema_filter_provider to point to theSchemaFilterProvider 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com