jjzjj

java - @PrePersist 正在被调用并修改实体,但没有写入数据库

coder 2023-10-06 原文

我正在使用 Hibernate 和 MySQL 在 Spring MVC 中开发一个应用程序,但我遇到了一个问题。我正在尝试使用 @PrePersist 注释在我的 Java 实体中填充我最后修改的字段。我已经调试了代码,正在调用方法并设置值。但是,数据库引发了空冲突,因为它没有写出 @PrePersist 方法添加的值。有谁知道如何解决这个问题,将数据写入数据库?

仅供引用,除了更改日期外,我还想使用这些 JPA 注释来执行某些业务逻辑或使用与注释类似的东西。

代码:

@Entity
@Table(name = "account")
public class Account {
    @Column(name = "modified_on")
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "MM")
    @NotNull()
    private Calendar modifiedOn;
... getters, setter and other stuff

    @PrePersist
    public void prePersist() {
        Calendar now = Calendar.getInstance();
        this.createdOn = now;
        this.modifiedOn = now;
    }


    @PreUpdate
    public void preUpdate() {
        Calendar now = Calendar.getInstance();
        this.modifiedOn = now;
    }

applicationContext-Persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xmlns:jdbc="http://www.springframework.org/schema/jdbc"
             xmlns:jee="http://www.springframework.org/schema/jee" 
             xmlns="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                            http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/jdbc
                            http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
                            http://www.springframework.org/schema/jee
                            http://www.springframework.org/schema/jee/spring-jee-3.2.xsd                            
                            http://www.springframework.org/schema/data/jpa 
                            http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
     <repositories base-package="${repositoryPackageName}" />
    <beans:bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    <beans:bean id="exceptionTranslator" class="org.springframework.orm.hibernate4.HibernateExceptionTranslator" />
    <beans:bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
        <beans:property name="entityManagerFactory" ref="entityManagerFactory" />
    </beans:bean>
    <beans:bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
        <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <beans:property name="driverClassName" value="${database.driverClassName}" />
            <beans:property name="url" value="${database.url}" />
            <beans:property name="username" value="${database.username}" />
            <beans:property name="password" value="${database.password}" />
        </beans:bean>
        <beans:bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
            <beans:property name="dataSource" ref="dataSource" />
            <beans:property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter" />
            <beans:property name="packagesToScan" value="${scanPackageName}" />
            <beans:property name="jpaProperties">
                <beans:props>
                    <beans:prop key="hbm2ddl.auto">validate</beans:prop>
                    <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
                    <beans:prop key="hibernate.query.substitutions">true '1', false '0'</beans:prop>
                    <beans:prop key="hibernate.generate_statistics">true</beans:prop>
                    <beans:prop key="hibernate.show_sql">false</beans:prop>
                    <beans:prop key="hibernate.format_sql">true</beans:prop>
                    <beans:prop key="hibernate.hbm2ddl.auto">validate</beans:prop>
                </beans:props>
            </beans:property>
        </beans:bean>
</beans:beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation=
    "http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.2.xsd"
    >
    <context:property-placeholder location="classpath:META-INF/spring/*.properties" />
    <context:property-placeholder location="classpath:META-INF/properties/*.properties"/>    
    <context:component-scan base-package="${doaminPackageName}"/>
    <context:component-scan base-package="${repositoryPackagename}"/>
    <context:component-scan base-package="${repositoryPackageName}" >
    <context:exclude-filter type="custom" expression="ourapp.util.TestClassFilter"/>
    </context:component-scan>
    <context:component-scan base-package="${utilBeanPackageName}"/>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.server.host}" />
        <property name="port" value="${mail.server.port}" />
        <property name="protocol" value="${mail.server.protocol}" />
        <property name="username" value="${mail.server.username}" />
        <property name="password" value="${mail.server.password}" />
        <property name="javaMailProperties">
            <util:properties location="classpath:META-INF/spring/javamail.properties" />
        </property>
    </bean> 
</beans>

applicationContext-web.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p" 

    xsi:schemaLocation=
    "http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/jee
    http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-3.2.xsd"
    >
    <context:component-scan base-package="${controllerPackageName}"/>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>

    <mvc:resources location="/, classpath:/META-INF/web-resources/" mapping="/resources/**"/>

    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" p:paramName="lang"/>
    </mvc:interceptors>
    <mvc:view-controller path="/uncaughtException"/>
    <mvc:view-controller path="/resourceNotFound"/>
    <mvc:view-controller path="/dataAccessFailure"/>

    <bean class="org.springframework.context.support.ReloadableResourceBundleMessageSource" id="messageSource"  p:fallbackToSystemLocale="false">
        <property name="basenames">
            <list>
                <value>META-INF/web-resources/i18n/accountCreation/messages</value>
                <value>META-INF/web-resources/i18n/accountCreation/application</value>
                <value>META-INF/web-resources/i18n/accountCreation/errors</value>
                <!-- Keep Global resource bundles at the bottom, they are checked last -->
                <value>META-INF/web-resources/i18n/global_messages</value>
                <value>META-INF/web-resources/i18n/global_application</value>
                <value>META-INF/web-resources/i18n/global_errors</value>
            </list>
        </property>
    </bean>
    <bean class="org.springframework.web.servlet.i18n.CookieLocaleResolver" id="localeResolver" p:cookieName="locale">
        <property name="defaultLocale" value="en"/>
    </bean>
    <bean class="org.springframework.ui.context.support.ResourceBundleThemeSource" id="themeSource"/>
    <bean class="org.springframework.web.servlet.theme.CookieThemeResolver" id="themeResolver" p:cookieName="theme" p:defaultThemeName="standard"/>
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:defaultErrorView="exceptions/uncaughtException">
        <property name="exceptionMappings">
            <props>
                <prop key=".DataAccessException">exceptions/dataAccessFailure</prop>
                <prop key=".NoSuchRequestHandlingMethodException">exceptions/resourceNotFound</prop>
                <prop key=".TypeMismatchException">exceptions/resourceNotFound</prop>
                <prop key=".MissingServletRequestParameterException">exceptions/resourceNotFound</prop>
            </props>
        </property>
    </bean>

    <!-- Enable this for integration of file upload functionality -->
    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"/>
<!-- TymeLeaf Settings -->
<!-- THYMELEAF: Template Resolver for webapp pages   --> 
    <bean class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" id="templateResolver">
      <property name="prefix" value="/WEB-INF/templates/"/>
      <property name="suffix" value=".html"/>
      <property name="templateMode" value="HTML5"/>
    </bean>
<!-- THYMELEAF: Template Engine (Spring3-specific version) -->     
    <bean class="org.thymeleaf.spring3.SpringTemplateEngine" id="templateEngine">
      <qualifier value="templateEngine"/>
      <property name="templateResolver" ref="templateResolver"/>
    </bean>
<!-- THYMELEAF: View Resolver - implementation of Spring's ViewResolver interface --> 
    <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
      <property name="templateEngine" ref="templateEngine"/>
    </bean>
</beans>

最佳答案

如果您的应用程序被配置为连接到 JPA 实体的方法中,如果您直接设置字段,它可能不会跟踪更改。尝试使用 setter 方法:

@PrePersist
public void prePersist() {
    Calendar now = Calendar.getInstance();
    this.setCreatedOn(now);
    this.setModifiedOn(now);
}


@PreUpdate
public void preUpdate() {
    Calendar now = Calendar.getInstance();
    this.setModifiedOn(now);
}

此外,如 a simily question 的回答中所述,这些注释行为是依赖于实现的:

Note that it is implementation-dependent as to whether PreUpdate and PostUpdate call- backs occur when an entity is persisted and subsequently modified in a single transaction or when an entity is modified and subsequently removed within a single transaction. Portable applications should not rely on such behavior.

所以这可能取决于您如何加载和保留您的实体。

关于java - @PrePersist 正在被调用并修改实体,但没有写入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18884639/

有关java - @PrePersist 正在被调用并修改实体,但没有写入数据库的更多相关文章

  1. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  2. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  3. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  4. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  5. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  10. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

随机推荐