gpt4 book ai didi

java - 未加载新创建的行中的默认值

转载 作者:行者123 更新时间:2023-11-29 18:15:46 24 4
gpt4 key购买 nike

我有一个 MySQL 表:

mysql> show create table items\G
*************************** 1. row ***************************
Table: items
Create Table: CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
1 row in set (0.02 sec)

我通过实体类从 Java 程序创建新行:

@Entity
@Table(name = "items", schema = "office_db")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Items.findAll", query = "SELECT i FROM Items i"),
@NamedQuery(name = "Items.findById", query = "SELECT i FROM Items i WHERE i.id = :id"),
@NamedQuery(name = "Items.findByName", query = "SELECT i FROM Items i WHERE i.name = :name"),
@NamedQuery(name = "Items.findByCreated", query = "SELECT i FROM Items i WHERE i.created = :created")
})
public class Items implements Serializable {

@Column(name = "name",length = 128)
private String name;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "created")
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@OneToMany(mappedBy = "itemId")
private Collection<Documents> documentsCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "items")
private Collection<ItemAttributes> itemAttributesCollection;
(more stuff ...)

我只设置了 NAME 列,正如预期的那样,默认设置了 ID 和 CREATED:

mysql> select * from items;
+----+--------+---------------------+
| id | name | created |
+----+--------+---------------------+
| 2 | Case 2 | 2017-10-31 13:47:52 |
| 3 | Case 3 | 2017-10-31 13:48:02 |
+----+--------+---------------------+
2 rows in set (0.00 sec)

但是,当我稍后在同一 session 中将表重新加载到 Java 中时:

public List<Items>findItems(){
TypedQuery<Items> query=
em.createNamedQuery("Items.findAll",Items.class);

return query.getResultList();
}

ID 列已正确加载,但 CREATED 列显示为空白。如果我重新启动应用程序(在 glassfish 服务器上运行),CREATED 将正确显示。我的猜测是,造成这种差异的原因是 ID 上的 @GenerateValue 注释,但我似乎无法将其应用于 CREATED 字段,或者至少不能天真地这样做。加载生成的时间戳的正确方法是什么?

最佳答案

看来,我的难题的答案是调用 em.refresh(),根据此:Invalidating JPA EntityManager session - 这是针对 Hibernate 的,但对于 EclipseLink 来说似乎是一样的。就我而言,我遇到了异常,但我将在另一个问题中发布该异常。

关于java - 未加载新创建的行中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47037245/

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