0

I’m looking at the out of the box options (number / date) for @Version in hibernate. I have number working as I would expect - sets version to 0 on initial insert, increments automatically on update, doesn’t increment or get in the way updating with no change. I wanted to look at using Date and essentially modified my working code sample from Long to Date. This does not work and I was wondering if anyone can help me ?

I am using 5.3.6.Final (with Spring)

I have this entity

@Entity
@Table (name="Names")
public class Names implements Serializable {
  private static final long serialVersionUID = 1L;
  private Long id;
  private String name;
  private Date version;

  @Id
  @Column(name="id", nullable=false)
  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id= id;
  }

  @Column(name="NAME", length=100)
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Version
  public Date getVersion() {
    return version;
   }

  public void setVersion(Date version) {
    this.version = version;
  }
}

I have this simple test

@Test
public void test_1 () {
  Names n = new Names ();

  //1st record
  n.setId(1L);
  n.setName(“John Doe”);
  System.out.println("SAVE 1 BEFORE ");
  nameService.saveRuleOfEngagement(roE);
  System.out.println("SAVE 1 AFTER ");

There is nothing of real interest in the service I don’t think ?

public void saveName(Names n) {

  Session currentSession = sessionFactory.getCurrentSession();
  currentSession.saveOrUpdate(n);
}

So this worked with version as a long but now fails on update. In fact it doesn’t try to update. So first run of test puts

1, “John Doe”, 2019-01-28 11:04:55.314

If I run the same again (with the same data or a changed name) I get

SAVE 1 BEFORE
Hibernate:
insert
into
“Names”
(“NAME”, version, “id”)
values
(?, ?, ?)
2019-01-28T11:07:27,008 [main] [WARN] [org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions(129)] - SQL Error: 0, SQLState: 23505
2019-01-28T11:07:27,008 [main] [ERROR] [org.hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions(131)] - ERROR: duplicate key value violates unique constraint “Names_pkey”
Detail: Key (“id”)=(1) already exists.

When it was using Long and working it was doing a select then an update ? Now it goes straight to insert and fails. All the help, official and unofficial that I have seen implies this should work out of the box ? Is there something obvious I have done wrong ?

1 Answers1

0

I don't think Hibernate supports a date as an incremental version field, and even if it does it you're linking the versioning to something (an incremental value) to something whose increment "meaning" does not follow that pattern. So as a best practice I would keep the version as a long, and use another field such as "last update" to keep the last date it was changed.

JayZee
  • 851
  • 1
  • 10
  • 17