gpt4 book ai didi

java - hibernate中如何获取当前session

转载 作者:行者123 更新时间:2023-12-02 09:09:17 24 4
gpt4 key购买 nike

我试图在 hibernate 状态下获取当前 session 以创建条件查询,但出现错误。

这是我的代码:

数据源.xml:

    <bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" ref="persistenceUnit" />
<property name="jpaProperties" ref="jpaProperties" />
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="globalRollbackOnParticipationFailure" value="true" />
</bean>

<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" ref="sqlDialect" />
</bean>

java 类:

    @Autowired
private SessionFactory sessionFactory;
Session session = sessionFactory.getCurrentSession();

FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
List<Product> bookResult = new ArrayList<>();
try {
// This will ensure that index for already inserted data is created.
fullTextEntityManager.createIndexer().startAndWait();
QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();
org.apache.lucene.search.Query query = qb.keyword().onFields("name").matching("cocacola").createQuery();
javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(query, Product.class);

Criteria criteria = session.createCriteria(Product.class);
criteria.add(Restrictions.eq("category.supermarket", "mercadona"));

List<Product> productos = criteria.list();

但出现此错误:

org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)

如何解决这个问题?

最佳答案

您是否已添加到 servlet-context.xml

<tx:annotation-driven transaction-manager="transactionManager" />

使用@Transaction?

还要检查 @Autowired 是否正常工作,例如 class.java 中的 System.out.println(sessionFactory) 以确保它不为 null。

关于java - hibernate中如何获取当前session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26557926/

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