我試圖實現一個自動增加「版本」列值的DAO。該版本不是主要關鍵。問題是我以前試過「@GeneratedValue」的值,但它沒有工作,並且sql給出了一條消息這隻適用於主鍵列,所以我不得不使用lastUpdate值並增加一個值,但是這不起作用,並且爲插入值保持傳遞1。JPA將列值增加1
這裏是我的代碼:
@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;
}
}
我認爲,目前還不清楚你想要什麼。它是否像[http://stackoverflow.com/questions/2572566/java-jpa-version-annotation]一樣。更新實體時的版本? – Jens
不是版本名稱是爲了別的。我只想增加一個值,每次都有一個新的插入 – user261002
你想更新一個稱爲版本的字段,或者你試圖創建一個增量版本的新對象 – fmucar