AKA
AKA

Reputation: 638

How to set @Column name dynamically in Hibernate

I am trying to set column name dynamically in a class(given below) but in @Column it need constant value as name.

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;
}

above code give me error: Attribute value must be constant

Please suggest me to give pre_col_name_created value dynamically from other class in @Column.

I already refer below links:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23

my goal is: I am creating 10 tables and all tables contain created column but prefix with different value that set as per Data model class.

for ex.: tables abc and qwe table abc has id,a_column(varchar) and table qwe has id, q_column(varchar)

Using @Transient I got error:

transient error

Upvotes: 4

Views: 3992

Answers (2)

ankit
ankit

Reputation: 2845

Below code is solution for you:

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;
    }
}

Common.java

@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;
    }
}

In above code there is Test class which you can use as classes where you want to change name of column and In class Common you can define type of common column you want.

Below is screenshot of Database: screenshot

I am waiting for you comment.Thanks

Upvotes: 1

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

Simply you cannot, hibernate mapping will be evaluated when initializing the datasrouce beans which is in the startup of your application.

Upvotes: 1

Related Questions