我正在尝试实现一个自动增加“版本”列值的DAO。该版本不是主要关键。问题是我之前尝试过“@GeneratedValue”值,但它没有用,而且sql给出了一条消息这只允许一个主键列,所以我不得不使用lastUpdate值并增加它是一个值,但这不起作用,并且它继续为插入值传递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;
}
}
答案 0 :(得分:2)
在JPA 2.0中,有@Version
注释。
您只需将注释添加到您希望成为版本字段的字段中,如下所示:
@Entity
public class MyEntity implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@Version
private Long version;
//...
}
答案 1 :(得分:1)
尝试选择最大版本,并更新值+ 1.
public void incrementVersion() {
Version lastUpdate = (Version) em.createQuery("SELECT max (c.version) FROM X c") .setMaxResults(1).getResultList();
int ver = lastUpdate.getVersion() + 1;
lastUpdate.setVersion(ver);
em.persist(lastUpdate);
}
答案 2 :(得分:-1)
我认为你不应该通过JPA来解决这个问题。您可以为表格创建触发器以自动增加"版本"每次更新行时的值。
如果你以MySQL为例:
CREATE TRIGGER version_trigger BEFORE UPDATE ON `your_table`
FOR EACH ROW
SET NEW.version = (OLD.version + 1)