当前位置: 首页 > 知识库问答 >
问题:

jpa-entitylistener-@prepersisted和@preupdate成功工作,但@postpersisted和@postupdate不工作

支洋
2023-03-14

下面是我的代码

实体->区域


import com.pete.bibliogere.modelo.listeners.EntidadeOperacoes;
import com.pete.bibliogere.modelo.listeners.EntidadeOperacoesInterface;

@Entity
@Table(name = "areas")
@EntityListeners(value = EntidadeOperacoes.class)
public class Area implements Serializable, EntidadeOperacoesInterface {

    @Column(updatable = false, name = "data_registo")
    private LocalDate dataRegisto;

    @Column(name = "data_alteracao")
    private LocalDate dataAlteracao;

... Some Getters, Setters and other attributes omited...

@Override
    public void setDataRegisto(LocalDate data_registo) {
        this.data_registo = data_registo;
    }

    @Override
    public void setDataAlteracao(LocalDate data_alteracao) {
        this.data_alteracao = data_alteracao;
    }
}

接口,用于实体共享相同的外部EntityListener

public interface EntidadeOperacoesInterface {

    public void setDataRegisto(LocalDate data_registo);

    public void setDataAlteracao(LocalDate data_alteracao);
}
public class EntidadeOperacoes {

    @PostPersist
    public void antesRegistar(EntidadeOperacoesInterface entidade) {
        System.out.println("-------- Inserindo data Inserção ------");
        entidade.setDataRegisto(LocalDate.now());
        System.out.println("-------- Fim Inserção ------");

    }

    @PostUpdate
    public void depoisAlteracao(EntidadeOperacoesInterface entidade) {
        System.out.println("-------- Data Atualização ------");
        entidade.setDataAlteracao(LocalDate.now());
        System.out.println("-------- Fim ------");

    }
public final class AreaController {

   private EntityManager em;
   private Validator validator;
   private AreaDao dao;

   public void registar(String nome, String localizacao) {
       validator = ValidatorUtil.getValidator();
       em = JpaUtil.getEntityManager();

       em.getTransaction().begin();
       dao = new AreaServico(em, validator);
       dao.registar(new Area(nome.trim(), localizacao.trim()));
       em.getTransaction().commit();

       em.close();
       ValidatorUtil.close();
   }

   public void alterar(long codigo, String nome, String localizacao) {
       validator = ValidatorUtil.getValidator();
       em = JpaUtil.getEntityManager();

       em.getTransaction().begin();
       dao = new AreaServico(em, validator);
       dao.atualizar(new Area(codigo, nome, localizacao));
       em.getTransaction().commit();

       em.close();
       ValidatorUtil.close();

   }

// Testing Purposes
   public static void main(String[] args) {

       AreaController ac = new AreaController();

       // Persiste area
       ac.registar("Area 1", "Localização 1");
   }

public class AreaServico implements AreaDao {

    private EntityManager em;
    private Validator validator;

    public AreaServico(EntityManager em, Validator validator) {
        this.em = em;
this.validator = validator;
    }

    @Override
    public void registar(Area area) {
        Set<ConstraintViolation<Area>> constraintViolations = validator.validate(area);

        if (constraintViolations.iterator().hasNext()) {
            JOptionPane.showMessageDialog(null, constraintViolations.iterator().next().getMessage(), "Atenção!", JOptionPane.ERROR_MESSAGE);
        } else {
            if (areaExiste(area.getNome())) {
                JOptionPane.showMessageDialog(null, "Erro: A área digitada já existe."
                        + "\nCertifique-se de escolher outro nome!", "Area existente!", JOptionPane.ERROR_MESSAGE);
            } else {
                em.persist(area);
            }
        }
    }

@Override
    public void atualizar(Area area) {
        Area areaEncontrada = em.find(Area.class, area.getCodigo());
        Set<ConstraintViolation<Area>> constraintViolations = validator.validate(area);

        if (areaEncontrada != null) {
            if (constraintViolations.iterator().hasNext()) {
                JOptionPane.showMessageDialog(null, "Erro: " + constraintViolations.iterator().next().getMessage());
            } else {
                if (areaExiste(area.getCodigo(), area.getNome())) {
                    JOptionPane.showMessageDialog(null, "Erro: Já existe uma área com este nome.\n"
                            + "Certifique-se de escolher um nome diferente!", "Area existente!", JOptionPane.ERROR_MESSAGE);
                } else {
                    areaEncontrada.setNome(area.getNome());
                    areaEncontrada.setLocalizacao(area.getLocalizacao());
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "Erro: A área digitada não existe!");
        }
    }


下面是我执行上面的Main方法时的控制台日志

Handling #sessionFactoryCreated from [org.hibernate.internal.SessionFactoryImpl@37b52340] for TypeConfiguration

    select
        area0_.codigo as codigo1_0_,
        area0_.data_alteracao as data_alt2_0_,
        area0_.data_registo as data_reg3_0_,
        area0_.localizacao as localiza4_0_,
        area0_.nome as nome5_0_ 
    from
        areas area0_ 
    where
        upper(area0_.nome)=?
binding parameter [1] as [VARCHAR] - [AREA 1]

    insert 
    into
        areas
        (data_alteracao, data_registo, localizacao, nome) 
    values
        (?, ?, ?, ?)
binding parameter [1] as [DATE] - [null]
binding parameter [2] as [DATE] - [null] /* This shouldn't be null, but LocalDate.now() */
binding parameter [3] as [VARCHAR] - [Localização 1]
binding parameter [4] as [VARCHAR] - [Area 1]
Depois de Inserir registo - Inicio: 1934663431---
Depois de Inserir registo - Fim:1934663440---
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time:  6.344 s
Finished at: 2020-10-29T09:44:24+02:00

下面是我的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.pete</groupId>
    <artifactId>BiblioGere</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-agroal</artifactId>
            <version>5.4.22.Final</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator-osgi-karaf-features</artifactId>
            <version>6.1.6.Final</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.el</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator-cdi</artifactId>
            <version>6.1.6.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.18</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>5.4.22.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports -->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.15.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
    </dependencies>
</project>

共有1个答案

周鸿云
2023-03-14

您在dataRegisto字段上设置updatable=false,因此设置器不更新数据库中的值似乎是正常的。

@PostUpdate在结束会话后调用。你能试着加上:

@Autowired
private EntityManager entityManager;

调用update之后:

entityManager.flush();
 类似资料:
  • 最后是持久性上下文配置: 我很感谢你的帮助。

  • 我试图通过在一个事务中运行多个save方法来原子化地保存许多实体,因此如果其中任何一个方法失败,所有这些方法都将被丢弃(回滚)。我尝试了很多方法,但似乎没有什么效果: BookingResource。java: ReservationRepository。java: Reservation.java: stacktrace是: 那么,这里发生了什么?我如何解决它?我试图公开这些方法,更改事务策略,

  • 我正在使用Spring Data JPA和Hibernate开发一个应用程序,并尝试使用EHCache启用二级缓存。我将我的应用程序分成两个项目: CoreDataFacade:在这里,我使用QueryDSL、Spring data JPA和Hibernate以及Ehcache定义了数据访问操作。 QueryComponent:是使用CoreDataFacade项目访问数据的spring启动项目。

  • 我有一个JPA@Entity类,它现在已经使用@Prepersisted很长一段时间了。今天,我想在需要实体ID的地方添加一些功能。这个ID是在持久化过程中由数据库中的HIBERNATE_SEQUENCE生成的。它通常设置在em.persist(实体)之后。

  • 在webapp中,我使用Spring AOP在来电时检查服务的授权,并在返回结果时管理消息(info、warn、error)。使用方面可以节省代码行并概括服务的行为(而且看起来很性感^^)。 所以我在应用程序上下文中有这种类型的conf 我的方面看起来是这样的: 在执行任何标记为的方法之前,应该触发方法,这是一种解脱。

  • 我安装了android Studio..一切正常。现在突然之间,所有的自动完成功能都不起作用了…我可以在任何地方输入任何东西没有变量检查,没有函数或检查任何东西的帮助。我仍然可以编译这个项目,当它发生时,我会得到错误。 有谁能帮我解决这个问题吗。