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

时间:2017-10-31 13:59:19

标签: java mysql jpa

我有一个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)

我通过Entity类从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)

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

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

    return query.getResultList();
}

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

1 个答案:

答案 0 :(得分:0)

看来,我的难题的答案是调用em.refresh(),根据这个:Invalidating JPA EntityManager session - 这适用于Hibernate,但对于EclipseLink来说似乎是相同的。在我的情况下,我遇到了一个例外,但我会在另一个问题中发布。