gpt4 book ai didi

spring-boot - java.lang.IllegalStateException : Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead 错误

转载 作者:行者123 更新时间:2023-12-02 03:51:19 42 4
gpt4 key购买 nike

伙计们。我想借助 Hibernate Search 在我的 Spring Boot 应用程序中创建全文搜索。我遇到了这样一个异常:java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead.在线发生

entityManager.getTransaction().begin();

这是我的代码

@Repository
public class HibernateSearch {
@PersistenceContext
private EntityManager entityManager;

@Transactional
public List<Manual> fulltextSearching(String keyword){

FullTextEntityManager fullTextEntityManager =
org.hibernate.search.jpa.Search.getFullTextEntityManager(entityManager);
entityManager.getTransaction().begin();

QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity(Manual.class).get();
org.apache.lucene.search.Query luceneQuery = qb
.keyword()
.onFields("name")
.matching(keyword)
.createQuery();

javax.persistence.Query jpaQuery =
fullTextEntityManager.createFullTextQuery(luceneQuery, Manual.class);

@SuppressWarnings("unchecked")
List<Manual> result = jpaQuery.getResultList();

entityManager.getTransaction().commit();
entityManager.close();
return result;
}

我的实体:

@Entity
@Table(name = "manual")
@Getter
@Setter
@NoArgsConstructor
@Indexed
public class Manual {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "manual_id")
private Long id;

@NotNull
@Column(name = "manual_name")
@Field
private String name;
}

我的属性:

spring.jpa.properties.hibernate.search.default.directory_provider = filesystem
spring.jpa.properties.hibernate.search.default.indexBase = D:\\Java

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

我的 Maven 依赖项:

    <dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.7.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>

如果您需要其他信息来回答我的问题,请说,我会添加。我搜索了网络,但仍然找不到答案。如果您能解决我的问题,我将非常高兴。

最佳答案

也许你应该从 EntityManagerFactory 获取 entityManager:

@Autowired
private EntityManagerFactory emf;
...
EntityManager entityManager = emf.createEntityManager();

关于spring-boot - java.lang.IllegalStateException : Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45325660/

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