I want to be able to store and fetch a counter value from my database which starts at zero and goes to Integer.MAX_VALUE. I want to be able to get the latest value and then have the value incremented so that the next time it is fetched it will equal (previous value + 1). It's not clear to me how I would go about doing this using Hibernate, and whether or not it's possible with all databases, i.e. perhaps some databases won't support this sort of sequencing.
One idea I have is that I could create a Hibernate object with an Integer counter field, set the original counter value to zero, save the object to my database, and then each time I need the next counter value I would get the object via a DAO method, get the counter field to use as the value in my Java code, increment the counter field in the object, and then update the object with the new incremented value. However this seems like a real hack, and I'm assuming/hoping that there's a more elegant way of doing this using Hibernate. The closest thing I've found so far looks to be using a generated property in my POJO, but I haven't been able to make it work, maybe because I need to set up my own generation strategy and I haven't found any documentation which describes how you would do that. I'm afraid I'm barking up the wrong tree by taking that approach, but I can't find anything else which looks to be an appropriate solution. As an example below is what I've tried to do, but again it's not working as I'd like -- the counter field is always null rather than being a generated sequence value as I was hoping for:
Code:
@Entity(name = "COUNTER")
public class Counter
implements Serializable
{
private Long id;
private Integer value;
@Column(name = "VALUE", nullable = true, insertable = false, updatable = false)
@Generated(GenerationTime.ALWAYS)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer getValue()
{
return value;
}
@Id
@Column(name = "COUNTER_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId()
{
return id;
}
public void setValue(final Integer value)
{
this.value = value;
}
public void setId(final Long id)
{
this.id = id;
}
}
I'm using Hibernate version 3.2.6.GA and Hibernate Annotations version 3.4.0.GA. I'm testing with an embedded HSQL database.
If anyone has done this before and can give me any ideas/advice I'd really appreciate the help. Thanks in advance.
--James
Code: