JPA - 使用时间戳修改自动生成的链接表
我正在寻找一种方法来扩展具有附加时间戳列的一对多关系中两个实体之间自动生成的链接表。
目的是什么? 每个实体本身都有一个时间戳,显示最后一次更改的时间。但没有办法 看看所做的改变。我们有必要了解地点和事件之间的分配是在什么时间进行的。
@Entity
public class Place{
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private final List <Event> events = new ArrayList<Event>();
....
}
该数据库包含三个表。地点、事件和地点_事件。 表 PLACE_EVENT 有两列:PLACE_ID 和 EVENT_ID。
我想要第三列“CREATED”,带有简单的时间戳。 有什么方法可以自动生成此时间戳。我不想自己创建一个新的实体 PLACE_EVENT 。
我不确定这是否可能,但我很感激任何提示。
我在 eclipselink 中使用 jpa 2.0 和 db2 驱动程序。
I'm searching for a way to extend auto generated linktables between two entities in an OneToMany relationship with an additional timestamp column.
What is the aim?
Each entity itself has a timestamp that shows the time of the last change. But there is no way
to see the kind of changes that were made. It is nesseccary for us to see at what time the assignment between Place and Event was made.
@Entity
public class Place{
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private final List <Event> events = new ArrayList<Event>();
....
}
The DB contains three tables. PLACE, EVENT and PLACE_EVENT.
The table PLACE_EVENT has got two columns: PLACE_ID and EVENT_ID.
I want a third Column "CREATED" with a simple timestamp.
Is there any way to generate this timestamp in an automated way. I dont want to create a new Entity PLACE_EVENT by myself.
I'm not sure if this is possible, but i'm grateful for any hints.
I'm using jpa 2.0 in eclipselink and a db2 driver.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以自己创建表(即不依赖于实体的自动模式创建),并添加默认值设置为
now()
的时间戳列。但要注意,有时(我记不清具体是哪种情况),当 Hibernate 将新实体 B 添加到 A 时,它会从连接表中删除引用 A 的所有行并重新插入它们。
另请注意,时间戳字段将填充到数据库中,但无法从 Hibernate 实体中获取。只有 SQL 查询才能访问时间戳。
You may create the table yourself (i.e. not rely on automatic schema creation from the entities), and add a timestamp column with a default value set to
now()
.But beware that sometimes (I can't remember exactly in which cases), when Hibernate adds a new entity B to A, it deletes all the rows referencing A from the join table and re-inserts them all.
Also note that the timestamp field will be populated in the database, but will not be available from the Hibernate entities. Only SQL queries will be able to access the timestamp.
如果您只想将时间戳记存储在数据库中,则可以使用触发器来生成时间戳记。
您还可以使用 DescriptorCustomizer 覆盖映射的 insertSQL 以包含服务器的时间戳。
如果您想要恢复时间戳,那么您需要将连接表映射为实体,以便有地方存储数据。
You could use a trigger to generate the timestamp if you just want it on the database.
You could also override your mapping's insertSQL to include the server's timestamp using a DescriptorCustomizer.
If you want the timestamp back, then you will need to map the join table as an Entity to have some place to store the data.