Dmitry Senkovich
Dmitry Senkovich

Reputation: 5911

Using @Column and @Formula in Hibernate at the same time

I've got a POJO and currently I'm getting a value from a single column. However, I'm moving to retrieve it using Hibernate @Formula (I select the latest record from another table). I want to go softly in order not to break anything.

So what I want to do is something like this:

class SomeDto {
    private someField;

    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @Formula("@NEW RETRIEVING LOGIC@")
    public getSomeField() {
    ...
}

so that I could be able to store the someField value in the PREVIOUS_FIELD_COLUMN and at the same time retrieve the value based on the new criteria.

However now it seems that Hibernate ignores the @Column annotation as I get the following error:

SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into

I see in logs that Hibernate skips PREVIOUS_FIELD_COLUMN in the insert statement being generated (doesn't list it and doesn't set the value from POJO).

Any help appreciated, thank you very much!

Upvotes: 1

Views: 1437

Answers (2)

ali akbar azizkhani
ali akbar azizkhani

Reputation: 2279

I think you will use ColumnTransformer instead of formula like this

  class SomeDto {
    private someField;


    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @ColumnTransformer(read = “@NEW RETRIEVING LOGIC@”)
    public getSomeField() {
    ...
  }

for more information see this https://www.thoughts-on-java.org/map-encrypted-database-columns-hibernates-columntransformer-annotation/

Upvotes: 2

Naros
Naros

Reputation: 21113

You could elect to just remap the previous value to a new field so it continues to be persisted for old records and you remap the old value to your @Formula logic.

public class SomeEntity {
  @Formula("your new formula logic");
  public Object getSomeField() {}

  @Column(name= "PREVIOUS_VALUE")
  public Object getPreviousValue() {}
}

Your post sounds like all you're concerned with technically is allowing your application to still interact with the object in the same way but you wish to source the value from somewhere else; however, being able to preserve access to and storage of the old value.

The above solution allows just that.

Upvotes: 2

Related Questions