gpt4 book ai didi

java - JPA将某列的值加一

转载 作者:行者123 更新时间:2023-11-29 07:59:51 25 4
gpt4 key购买 nike

我正在尝试实现一个自动增加“版本”列值的 DAO。该版本不是主键。问题是我之前尝试过“@GenerateValue”值,但它不起作用,并且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;
}
}

最佳答案

在 JPA 2.0 中,有 @Version 注释。

您只需将注释添加到您想要成为版本字段的字段,如下所示:

@Entity
public class MyEntity implements Serializable {

@Id
@GeneratedValue
private Long id;

private String name;

@Version
private Long version;

//...
}

看看:Java - JPA - @Version annotation

关于java - JPA将某列的值加一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24141930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com