I am trying to implement a DAO that increases the value of the "version" column automatically. The version is not a primay key. The problem is that I tried the "@GeneratedValue" value before, but it didnt work and sql was giving a message this is only allowed for a primarykey columns, so I had to use the lastUpdate value and increase it one value, but this doesn't work and it keeps passing 1 for the insert value.
here is my code :
@Repository
public class VersionDAO {
@PersistenceContext
private EntityManager em;
public void create(Version version) {
Version lastUpdate = (Version) em.createQuery("SELECT c FROM Version c ORDER BY c.uploadedtimestamp DESC")//
.setMaxResults(1).getResultList();
int ver = lastUpdate.getVersion() + 1;
version.setVersion(ver);
em.persist(version);
}
public void delete(Version version) {
em.remove(version);
}
}
@Entity
@Table(name = "version")
public class Version implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "version")
private Integer version;
@Column(name="uploadedtimestamp")
@Temporal(TemporalType.TIMESTAMP)
private Date uploadedtimestamp = new Date();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
Version cdi = (Version) obj;
return new EqualsBuilder().append(getId(), cdi.getId()).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37).append(getId()).toHashCode();
}
public Date getUploadedtimestamp() {
return uploadedtimestamp;
}
public void setUploadedtimestamp(Date uploadedtimestamp) {
this.uploadedtimestamp = uploadedtimestamp;
}
}