Java 如何在Hibernate中动态设置@Column name
我试图在类(如下所示)中动态设置列名,但在Java 如何在Hibernate中动态设置@Column name,java,hibernate,jpa,data-modeling,Java,Hibernate,Jpa,Data Modeling,我试图在类(如下所示)中动态设置列名,但在@column中,它需要常量值作为名称 public class Common { final String pre_col_name_created; public Common( String pre_col_name ) { this.pre_col_name_created = pre_col_name; } @Column( name = pre_col_name_created + "" ) pr
@column
中,它需要常量值作为名称
public class Common
{
final String pre_col_name_created;
public Common( String pre_col_name )
{
this.pre_col_name_created = pre_col_name;
}
@Column( name = pre_col_name_created + "" )
private String created;
}
上面的代码给了我一个错误:
请建议我在@Column
中给从其他类动态创建的pre\u col\u name\u值
我已经参考了以下链接:
我的目标是:创建10个表,所有表都包含created
列,但前缀具有不同的值,这些值是根据数据模型类设置的
例如:
表abc
和qwe
表abc
有id
,a_列(varchar)和
表qwe
具有id
,q\u列(varchar)
使用@Transient
我得到错误:
如果您不能,则在初始化应用程序启动时的datasrouce bean时,将评估hibernate映射。以下代码是您的解决方案:
Test.java
@Entity
@Filter(
name = "tenancyFilter",
condition = "et_created = :created"
)
@AttributeOverride(
name = "created",
column = @Column(
name = "et_created"
)
)
public class Test extends Common
{
@Id
@Column( name = "comp_id" )
private UUID id;
public UUID getId()
{
return id;
}
public void setId( UUID id )
{
this.id = id;
}
}
@MappedSuperclass
@EntityListeners( { AuditingEntityListener.class})
@FilterDef(
name = "tenancyFilter",
parameters = {@ParamDef(
name = "created",
type = "timestamp"
)}
)
public class Common
{
private Timestamp created;
public Timestamp getCreated()
{
return created;
}
public void setCreated( Timestamp created )
{
this.created = created;
}
}
Common.java
@Entity
@Filter(
name = "tenancyFilter",
condition = "et_created = :created"
)
@AttributeOverride(
name = "created",
column = @Column(
name = "et_created"
)
)
public class Test extends Common
{
@Id
@Column( name = "comp_id" )
private UUID id;
public UUID getId()
{
return id;
}
public void setId( UUID id )
{
this.id = id;
}
}
@MappedSuperclass
@EntityListeners( { AuditingEntityListener.class})
@FilterDef(
name = "tenancyFilter",
parameters = {@ParamDef(
name = "created",
type = "timestamp"
)}
)
public class Common
{
private Timestamp created;
public Timestamp getCreated()
{
return created;
}
public void setCreated( Timestamp created )
{
this.created = created;
}
}
在上面的代码中,有一个测试类,您可以将其用作要更改列名称的类,在“公共类”中,您可以定义所需公共列的类型
以下是数据库的屏幕截图:
我正在等待您的评论。谢谢我认为这是不可能的,但是,您可以使用一些VO类(如子类),然后将其映射到您需要的实体,只是提示您使用动态表的目标是什么?看起来像一个。您到底想解决什么问题?@Stefan请参考编辑问题。批注中的变量必须是常量。不能存在具有不同注释值的类实例。如前所述,使用子类并重写属性hanks-Ankit,但我遇到了错误:org.springframework.beans.factory.BeanCreationException:创建名为“entityManagerFactory”的bean时出错,该bean在类路径资源[org/springframework/boot/autoconfigure/orm/jpa/hibernatejbaconfiguration.class]中定义:调用init方法失败;嵌套异常为org.hibernate.AnnotationException:不能同时使用@entity和@MappedSuperclass:com.PostgressSpringBootGradle.PostgressSpringBootGradle.entity.Test对实体进行注释
@AKAggarwal请将中的@MappedSuperclass
从测试类中删除。因为@MappedSuperclass
和@entity
不起作用一起。谢谢你的帮助。@AKAggarwal欢迎你。