gpt4 book ai didi

java - Hibernate/JPA 在合并后获取数据库中具有默认值的列的值

转载 作者:行者123 更新时间:2023-11-30 10:41:29 26 4
gpt4 key购买 nike

案例:合并对象后,我想获取映射到数据库端具有默认值的列的字段值。

表格:

CREATE TABLE IF NOT EXISTS `db`.`OBJECT` (
`OBJECT_ID` INT NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(64) NULL,
`CREATED_ON` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`EDITED_ON` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

类:

@Entity
@Table(name="OBJECT")
public class SomeObject {
private int id;
private String name;
private Timestamp createdOn;
private Timestamp editedOn;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Column(name = "NAME")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Column(name = "CREATED_ON", insertable = false, updatable = false)
public Timestamp getCreatedOn() {
return createdOn;
}

public void setCreatedOn(Timestamp createdOn) {
this.createdOn = createdOn;
}

@Column(name = "EDITED_ON", insertable = false, updatable = false)
public Timestamp getEditedOn() {
return editedOn;
}

public void setEditedOn(Timestamp editedOn) {
this.editedOn = editedOn;
}
}

DAO:

@Transactional
public class ObjectDAO {
@PersistenceContext
private EntityManager entityManager;

public someObject merge(someObject someObject) {
return entityManager.merge(someObject);
}
}

我想做什么:

SomeObject someObject = new SomeObject();
someObject.setName("name");
SomeObject insertedObject = objectDAO.merge(someObject);
System.out.println(insertedObject.getId());
System.out.println(insertedObject.getEditedOn());

结果:对象被插入到数据库中,所有默认值都正确生成。

问题:为什么第二个 println 打印 null,但第一个 println 打印插入数据库的 Id 的正确值?

最佳答案

在你执行这一行之前:

System.out.println(insertedObject.getEditedOn());

您必须通过调用“刷新”(同步)您的更新:entityManager.flush();

关于java - Hibernate/JPA 在合并后获取数据库中具有默认值的列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38469049/

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