Java 休眠/JPA 中的@PreUpdate 和@Prepersist(使用会话)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4133287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:57:25  来源:igfitidea点击:

@PreUpdate and @Prepersist in hibernate/JPA (using session)

javahibernatejpajakarta-ee

提问by black sensei

I've hit a blocker adding a fix to an existing project.the main problem is that i'll like to use @Prepersistand @PreUpdatein the POJOto take care of LastModifiedfield (insert and update) using hibernate implementation of JPA with session.

我已经打了一个拦截器将修复到现有project.the主要问题是,我一定会喜欢使用@Prepersist,并@PreUpdatePOJO照顾LastModified使用Hibernate实现JPA与会议现场(INSERT和UPDATE)。

Reason ?: That change is required because there is a need to use liquibase 1.9.5and i know (since i've faced this before) that liquibase translate timestamp fied to datetime with default current_timestamp, and that is too bad for mysql database.

原因 ?:需要进行更改,因为需要使用,liquibase 1.9.5而且我知道(因为我之前遇到过这种情况)liquibase 将时间戳转换为具有默认 current_timestamp 的日期时间,这对于 mysql 数据库来说太糟糕了。

So i needed a way to have this set in code rather than in database so i could safely change timestamp field to datetime.then liquibase is happy, i'm happy.

所以我需要一种方法来在代码中而不是在数据库中设置这个,这样我就可以安全地将时间戳字段更改为日期时间。然后 liquibase 很高兴,我很高兴。

Now it seems that those interpreters are not been executed, with little search i found out that it's suitable using entityManager.That is currently out of question.So i'll like to know if is there a SIMPLEway around my problem, meaning having @Prepersistor @PreUpdateor even other workaround to set the lastModifiedfield still using session

现在似乎这些解释器没有被执行,经过很少的搜索,我发现它适合使用entityManager。这是目前没有问题的。所以我想知道是否有解决我的问题的简单方法,意思是有@Prepersist@PreUpdate或甚至其他解决方法来设置lastModified字段仍然使用会话

采纳答案by Pascal Thivent

Now it seems that those interpreters are not been executed, with little search i found out that it's suitable using entityManager.

现在似乎这些解释器没有被执行,经过很少的搜索,我发现它适合使用 entityManager。

Yes, the JPA callbacks won't work if you're using the SessionAPI.

是的,如果您使用SessionAPI ,则 JPA 回调将不起作用。

So I'll like to know if is there a SIMPLE way around my problem, meaning having @PrePersist or @PreUpdate or even other workaround to set the lastModified field still using session

所以我想知道是否有解决我的问题的简单方法,这意味着使用 @PrePersist 或 @PreUpdate 或什至其他解决方法来设置 lastModified 字段仍然使用会话

To my knowledge, there is no simple way around (if you're using Spring, MAYBEhave a look at this postthough).

据我所知,没有简单的方法(如果您使用的是 Spring,也许可以看看这篇文章)。

My suggestion for an Hibernate based solution would be to use events(and one or more interface(s)). Check Hibernate and last modified datefor an example.

我对基于 Hibernate 的解决方案的建议是使用事件(以及一个或多个接口)。以Hibernate 和上次修改日期为例。