gpt4 book ai didi

hibernate - Hibernate 事件监听器如何使用 HQL(命名查询)进行操作?

转载 作者:行者123 更新时间:2023-12-02 00:36:51 30 4
gpt4 key购买 nike

我创建了很多 hibernate 事件监听器,以捕获所有数据库事件,如加载、持久化、更新、删除等。所有事件都会被捕获,但命名查询不会被我的加载事件监听器捕获,我想问,我需要实现什么来捕获名称查询?

最佳答案

基本上,事件的参与取决于事件(监听器)的类型和获取数据的方式。尽管您是对的,但实际上使用实体查询(EntityManager.find...、Session.load...)和使用 HQL 查询之间显然存在差异。但是在 HQL 的情况下,HQL 查询是用作命名查询还是用作常规查询并不重要。

为了展示这一点,我使用 Spring Boot、Spring Data JPA 和 Hibernate 创建了一个小示例,因为使用这种组合很容易。效果类似于使用 Hibernate 的其他应用程序架构。

如果我们使用加载事件为例,如果您使用 EntityManager.find/Session.load 接收实体,则直接加载的实体只会传播 LoadEvent 类型的事件。使用 HQL(使用 Spring Data JPA 或纯 Hibernate),如果可疑实体作为关联间接获取,则只有这种特定类型的事件。与此相反,在所有情况下都会触发 PostLoadEvents。

这里有一些简单的类来尝试这个。

InterceptionByEventCandidate(我们要拦截的实体):

package com.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class InterceptionByEventCandidate {

public static final String FETCH_ALL_QUERY = "SELECT c FROM InterceptionByEventCandidate c";
public static final String FETCH_ALL_NAMED_QUERY = "selectAll";

@Id
@GeneratedValue
private long id;

private boolean interceptedOnLoad;

private boolean interceptedOnPostLoad;

public long getId() {
return id;
}

public boolean isInterceptedOnLoad() {
return interceptedOnLoad;
}

public void setInterceptedOnLoad(boolean interceptedOnLoad) {
this.interceptedOnLoad = interceptedOnLoad;
}

public boolean isInterceptedOnPostLoad() {
return interceptedOnPostLoad;
}

public void setInterceptedOnPostLoad(boolean interceptedOnPostLoad) {
this.interceptedOnPostLoad = interceptedOnPostLoad;
}

}

CandidateHost(需要主机来演示关联获取):

package com.example.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class CandidateHost {

public static final String FETCH_ALL_QUERY = "SELECT h FROM CandidateHost h JOIN h.candidate c";
public static final String FETCH_ALL_NAMED_QUERY = "selectAllHosts";

@Id
@GeneratedValue
private long id;

@OneToOne(cascade = CascadeType.PERSIST)
private InterceptionByEventCandidate candidate;

public InterceptionByEventCandidate getCandidate() {
return candidate;
}

public void setCandidate(InterceptionByEventCandidate candidate) {
this.candidate = candidate;
}

}

现在我们需要一个合适的监听器,为了方便起见,我们将上述两种类型的事件组合在一个 HqlEventListener 中:

package com.example.event;

import org.hibernate.HibernateException;
import org.hibernate.event.spi.LoadEvent;
import org.hibernate.event.spi.LoadEventListener;
import org.hibernate.event.spi.PostLoadEvent;
import org.hibernate.event.spi.PostLoadEventListener;
import org.springframework.stereotype.Component;

import com.example.model.InterceptionByEventCandidate;

@Component
public class HqlEventListener implements LoadEventListener, PostLoadEventListener {

private static final long serialVersionUID = -7248393324424903264L;

@Override
public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException {
final Object object = event.getResult();
if (object instanceof InterceptionByEventCandidate) {
((InterceptionByEventCandidate) object).setInterceptedOnLoad(true);
}
}

@Override
public void onPostLoad(PostLoadEvent event) {
final Object object = event.getEntity();
if (object instanceof InterceptionByEventCandidate) {
((InterceptionByEventCandidate) object).setInterceptedOnPostLoad(true);
}
}

}

要告诉 Hibernate 我们要处理哪些事件,我们需要一些配置:

package com.example.event;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EntityListenerConfiguration {

@PersistenceUnit
private EntityManagerFactory entityManagerFactory;

@Autowired
private HqlEventListener hqlEventListener;

@PostConstruct
protected void init() {
final SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
final EventListenerRegistry eventListenerRegistry = sessionFactory.getServiceRegistry()
.getService(EventListenerRegistry.class);

eventListenerRegistry.getEventListenerGroup(EventType.LOAD).appendListener(hqlEventListener);
eventListenerRegistry.getEventListenerGroup(EventType.POST_LOAD).appendListener(hqlEventListener);

}
}

为了提供和重用命名查询,我们将其存储在包信息文件中:

@NamedQueries({
@NamedQuery(name = InterceptionByEventCandidate.FETCH_ALL_NAMED_QUERY, query = InterceptionByEventCandidate.FETCH_ALL_QUERY),
@NamedQuery(name = CandidateHost.FETCH_ALL_NAMED_QUERY, query = CandidateHost.FETCH_ALL_QUERY) })

package com.example.event;

import org.hibernate.annotations.NamedQueries;
import org.hibernate.annotations.NamedQuery;

import com.example.model.CandidateHost;
import com.example.model.InterceptionByEventCandidate;

当然,如果它们表现出相同的行为,则需要一些 Spring Data JPA 存储库进行尝试。

InterceptionByEventCandidateRepository:

package com.example.repository;

import java.util.Set;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.example.model.InterceptionByEventCandidate;

@Repository
public interface InterceptionByEventCandidateRepository extends CrudRepository<InterceptionByEventCandidate, Long> {

@Query(InterceptionByEventCandidate.FETCH_ALL_QUERY)
@Transactional(readOnly = true)
Set<InterceptionByEventCandidate> findByHQL();

@Query(name = InterceptionByEventCandidate.FETCH_ALL_NAMED_QUERY)
@Transactional(readOnly = true)
Set<InterceptionByEventCandidate> findByNamedHQL();
}

候选主机库:

package com.example.repository;

import java.util.Set;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.example.model.CandidateHost;

@Repository
public interface CandidateHostRepository extends CrudRepository<CandidateHost, Long> {

@Query(CandidateHost.FETCH_ALL_QUERY)
@Transactional(readOnly = true)
Set<CandidateHost> findByHQL();

@Query(name = CandidateHost.FETCH_ALL_NAMED_QUERY)
@Transactional(readOnly = true)
Set<CandidateHost> findByNamedHQL();

}

那是很多示例代码,这里是一个(我不得不承认也是巨大的)测试来检查策略之间的事件差异:

package com.example.repository;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import com.example.model.CandidateHost;
import com.example.model.InterceptionByEventCandidate;

@RunWith(SpringRunner.class)
@Transactional
@SpringBootTest
public class HqlEventTests {

@Autowired
private CandidateHostRepository candidateHostRepository;

@Autowired
private InterceptionByEventCandidateRepository interceptionByEventCandidateRepository;

@PersistenceContext
private EntityManager entityManager;

@Before
public void setUp() {
final CandidateHost host = new CandidateHost();
final InterceptionByEventCandidate interceptionByEventCandidate = new InterceptionByEventCandidate();
host.setCandidate(interceptionByEventCandidate);
candidateHostRepository.save(host);
entityManager.flush();
entityManager.clear();
}

@Test
public void interceptCandidateAtFindingHostBySpringDataJpaHql() {
final Set<CandidateHost> result = candidateHostRepository.findByHQL();
verifyInterceptions(result.stream().findFirst().get().getCandidate(), true, true);
}

@Test
public void interceptCandidateAtFindingHostBySpringDataJpaNamedHql() {
final Set<CandidateHost> result = candidateHostRepository.findByNamedHQL();
verifyInterceptions(result.stream().findFirst().get().getCandidate(), true, true);
}

@Test
public void interceptCandidateAtFindingHostByHibernateHql() {
final Session session = entityManager.unwrap(Session.class);
final Query query = session.createQuery(CandidateHost.FETCH_ALL_QUERY);

verifyInterceptions(((CandidateHost) query.list().stream().findFirst().get()).getCandidate(), true, true);
}

@Test
public void interceptCandidateAtFindingHostByHibernateNamedHql() {
final Session session = entityManager.unwrap(Session.class);
final Query query = session.getNamedQuery(CandidateHost.FETCH_ALL_NAMED_QUERY);

verifyInterceptions(((CandidateHost) query.list().stream().findFirst().get()).getCandidate(), true, true);
}

@Test
public void interceptCandidateBySpringDataJpaHql() {
final Set<InterceptionByEventCandidate> result = interceptionByEventCandidateRepository.findByHQL();
verifyInterceptions(result.stream().findFirst().get(), false, true);
}

@Test
public void interceptCandidateBySpringDataJpaNamedHql() {
final Set<InterceptionByEventCandidate> result = interceptionByEventCandidateRepository.findByNamedHQL();
verifyInterceptions(result.stream().findFirst().get(), false, true);
}

@Test
public void interceptCandidateByHibernateHql() {
final Session session = entityManager.unwrap(Session.class);
final Query query = session.createQuery(InterceptionByEventCandidate.FETCH_ALL_QUERY);

verifyInterceptions((InterceptionByEventCandidate) query.list().stream().findFirst().get(), false, true);
}

@Test
public void interceptCandidateByHibernateNamedHql() {
final Session session = entityManager.unwrap(Session.class);
final Query query = session.getNamedQuery(InterceptionByEventCandidate.FETCH_ALL_NAMED_QUERY);

verifyInterceptions((InterceptionByEventCandidate) query.list().stream().findFirst().get(), false, true);
}

@Test
public void interceptCandidateByHibernateFind() {
long id = interceptionByEventCandidateRepository.findAll().iterator().next().getId();

entityManager.flush();
entityManager.clear();

final Session session = entityManager.unwrap(Session.class);
final InterceptionByEventCandidate candidate = session.load(InterceptionByEventCandidate.class, id);
verifyInterceptions(candidate, true, true);
}

private void verifyInterceptions(final InterceptionByEventCandidate candidate, final boolean expectedLoadEventState,
final boolean expectedPostLoadEventState) {
assertThat("Expected load state did not match!", candidate.isInterceptedOnLoad(), is(expectedLoadEventState));
assertThat("Expected postload state did not match!", candidate.isInterceptedOnPostLoad(),
is(expectedPostLoadEventState));
}
}

查看此测试,我们可以看到命名查询和常规查询之间没有区别。如果您担心其他类型的事件,我想扩展它很容易。

关于hibernate - Hibernate 事件监听器如何使用 HQL(命名查询)进行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4243381/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com