开发者

JPA @version - can it be used to calcualate version of a table entry

开发者 https://www.devze.com 2022-12-31 06:16 出处:网络
Please consider the following table (created using a corresponding entity) request ------- id requestor type version items

Please consider the following table (created using a corresponding entity)

request
-------
id requestor type version items 
1  a         t1   1        5
2  a         t1   2        3
3  b         t1   1        2
4  a         t2   1        4
5  a         t1   3        9 

The above is what I want to achieve. The version field is a calculated field others are user provided. Basically the request's version needs to be calculated based on the combination of requestor and the type. The first occurance with a given combination will have a version 1 then version 2 and so on.

I tried various things using @version on a different entity with just the three columns and joining the two entities using ManytoOne etc but I'm not able to get to the desired outcome. I dont want to confuse you with the things I tried.

Since the objective is simple there should be an easier way I suppose? Can you please help? - any help gr开发者_运维技巧eatly appreciated!

thanks in advance


The Version annotation is used to specify the version field or property of an entity class that serves as its optimistic lock value. I don't think this has anything to do with what you're looking for. Here are some ideas though:

  1. Use a trigger on insert.
  2. Use a SQL View.
  3. Use a provider specific extension for derived attributes like Hibernate's @Formula (this annotation that lets you map a property to an SQL expression rather than a table column).

To illustrate the latest option, you could declare something like this:

@Formula("(select count(r.id)+1 from Request r where r.requestor=requestor and r.type=type and r.id<id)")
public long getVersion() { return version; }
0

精彩评论

暂无评论...
验证码 换一张
取 消