Hibernate - How to persist computed column on database side

165 views Asked by At

Could someone help me to identify a solution, which would allow me to compute column's value on insert.

I have tried different combinations with @Formula and @Genarated. Is this even possible ? If so whats the alternative to persist a computed column ?

My persistance layer is managed by a JpaRepository

@SpringBootTest
@EnableTransactionManagement
@TestPropertySource("classpath:config/application-integrationtest.properties")
class CompetitorRepositoryItTest {

    @Autowired
    private CompetitorRepository competitorRepository;
    
    @Test
    @Transactional(transactionManager = "defaultTransactionManager")
    void createPartToContract() {

        Competitor competitor = this.createCompetitor(firstName,lastName, ...);
        return this.CompetitorRepository.save(competitor);
    }
    
}


my Class :

public class Competitor {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Generated(GenerationTime.INSERT)
    @Formula("(SELECT (COALESCE(MAX(rank), 0)+ 1) from Competitor c WHERE c.id = id)")
    @Column(name = "rank", insertable = true, updatable = false)
    private int rank;
}
1

There are 1 answers

0
Christian Beikov On

This kind of requirement is usually solved by creating a database trigger.