【问题标题】:Dynamically Changing Table Names动态更改表名
【发布时间】:2016-06-19 09:31:20
【问题描述】:

我目前正在使用具有读写表的数据库。

总是有两个表具有相同的模式,用一个数字作为后缀来区分,例如。表 1 和表 2。

现在,我可以从另一个来源获得当前号码。我必须用这个数字从对应的表中选择后缀匹配的。

现在,对于每个表,我都有一个包含架构的 @MappedSuperclass 和两个通过 @Table(name = "..1") 和 @Table(name = "..2") 指定表名的实现类。

这个解决方案有效,但现在我发现了很多缺点,担心还会有更多。还有其他更好的方法来解决这个问题吗?

不幸的是,我无法找到这种数据库机制的名称,因此我无法在互联网上找到任何其他来源。

提前谢谢你!

【问题讨论】:

  • 这是遗留系统还是什么?像这样使用表命名没有多大意义,这可能就是为什么你找不到很多关于它的信息的原因。您是否有机会重新设计以不使用两个不同的表?
  • 很遗憾没有。我必须按设计使用数据库..

标签: mysql hibernate jpa jakarta-ee


【解决方案1】:

最明显的解决方案:

    if ( num == 1 )
    {
      Table1 table1 = createTable1();
      table1.set...;
      entityManager.persist( table1 );
    } else
    {
      Table2 table2 = createTable2();
      table2.set...;
      entityManager.persist( table2 );
    }

或者通过名称调用构造函数(使用 Lombok 注释):

@Entity
@Data
public class CommonBase
{}

@Entity
@Data
public class Table1 extends CommonBase
{}

@Entity
@Data
public class Table2 extends CommonBase
{}

@Stateless
@LocalBean
public class CommonBaseBean
{
  @Inject
  private CommonBaseBUS commonBaseBUS;

  protected void clientCode()
  {
    Table0 t0 = (Table0) commonBaseBUS.createEntityByIndex( 0 );
    t0.set...();
    commonBaseBUS.persisEntity( t0 );

    Table1 t1 = (Table1) commonBaseBUS.createEntityByIndex( 1 );
    t1.set...();
    commonBaseBUS.persisEntity( t1 );
  }
}

@Dependent
class CommonBaseBUS
{
  @Inject
  private CommonBaseDAL commonBaseDAL;

  @Setter
  private String entityBaseName = "qualified.path.Table";

  public CommonBase createEntityByIndex( int index_ ) throws ClassNotFoundException
  {
    String entityName = entityBaseName + Integer.toString( index_ );
    return createEntityByName( entityName );
  }

  public void persisEntity( CommonBase cb_ )
  {
    commonBaseDAL.persistEntity( cb_ );
  }

  protected CommonBase createEntityByName( String entityName_ ) throws ClassNotFoundException
  {
    Class<?> c = Class.forName( entityName_ );
    try
    {
      return (CommonBase) c.newInstance();
    }
    catch ( InstantiationException | IllegalAccessException ex )
    {
      throw new ClassNotFoundException();
    }
  }
}

@Dependent
class CommonBaseDAL
{
  @PersistentContext
  private EntityManager em;

  public void persisEntity( CommonBase cb_ )
  {
    em.persistEntity( cb_ );
  }        
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 此代码回答问题的附加上下文可提高其长期价值.
  • 这是我想避免的明显解决方案。我最终使用了超类。唯一需要实际实现的是 jpa entitymanager,我正在通过硬编码枚举解析类
  • 您可以为它们使用超类,但我不知道:是否有任何共同属性?如果不是,那是个坏主意。错误的设计决策。
  • @Benjamin W:如果我告诉你我完全理解这个问题的意义,我不会说实话。但我不想贬低它。
猜你喜欢
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多