如何理解JPA实体管理员?

时间:2018-02-06 13:33:10

标签: hibernate jpa spring-boot

我在使用@Transactional注释的方法中包含以下代码库。我也注射了EntityManager

public Entity getEntity() {
  Query query = entityManager.createNativeQuery(
      "SELECT * from table WHERE .....",  MyEntity.class);
  List<MyEntity> results = query.getResultList();

  for (MyEntity entity : results) {
    try {
      Timestamp now = ....;
      // Update the field timestamp
      entity.setTimestamp(now);
      entityManager.merge(entity);
      return entity;
    } catch (Exception e) {
      continue;
    }
  }
}

我的实体有一个版本字段,注明@Version。所以我期望从上面的代码库中得到的是幸福的路径,没有例外,只有第一个实体应该在我的数据库中更新。然而,正在发生的事情是所有实体都会更新version字段为所有实体增加的位置。

我怎么能理解?

更新

我的部分实体代码如下所示:

@Entity
@EntityListeners(value=EntityListener.class)
@Table(name = "table_name")
public class Entity {

    @Id
    @GenericGenerator(name = "seq_name", strategy = "increment")
    @GeneratedValue(generator = "seq_name", strategy = GenerationType.SEQUENCE)
    @Column(updatable = false, nullable = false)
    private long uuid;

    @Version
    private long version;

  @JsonIgnore
    @Column(name = "timestamp")
    @Convert(converter = TSAttributeConvertor.class)
    private Timestamp timestamp;

    public long getUuid() {
        return uuid;
    }

    public void setUuid(long uuid) {
        this.uuid = uuid;
    }

    public long getVersion() {
        return version;
    }

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

  public Timestamp getTimestamp() {
    return timestamp;
  }

  public void setTimestamp(Timestamp timestamp) {
        this.timestamp = timestamp;
    }

}

0 个答案:

没有答案