人。我希望在Hibernate Search的帮助下在Spring Boot应用程序中创建全文搜索。我遇到了这样的异常:java.lang.IllegalStateException:不允许在共享的EntityManager上创建事务 - 使用Spring事务或EJB CMT。它在网上发生了
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
My 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>
如果您需要其他信息来回答我的问题,请说,我会添加它。我搜索了网但仍无法找到答案。 如果你解决我的问题,我会很高兴。
答案 0 :(得分:2)
也许你应该从entityManager
获得EntityManagerFactory
:
@Autowired
private EntityManagerFactory emf;
...
EntityManager entityManager = emf.createEntityManager();
答案 1 :(得分:0)
也许您应该使用@Transactional
中的javax.transaction package
注释。
为我工作。