java - Hibernate4报错createQuery is not valid without active transaction
天蓬老师
天蓬老师 2017-04-17 16:34:32
[Java讨论组]

就是在这里查询就出错了
@Override

public User get(int id) {
    Session session = sessionFactory.getCurrentSession();
    String sql = "from User where id = :id";
    Query query = session.**createQuery(sql)**;
    query.setParameter("id", id);
    query.setMaxResults(1);
    User user = (User)query.uniqueResult();
    return user;
}

spring的配置文件:



    
    
    
    
        
    

    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    
    
    
        
            
        
        
            
                
                    org.hibernate.dialect.MySQLDialect
                
                none
                true
                true
                true 1, false 0
                16
                2
                true
                true
                thread
            
        
        
        
    

    
        
    

    
    
    
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(1)
巴扎黑

原因是你的业务方法没有加上事务,看你用的是spring,可以使用spring的声明式事务。
给你段配置,你可以简单参考下

<tx:advice transaction-manager="transactionManager" id="txAdvice">
    <tx:attributes>
        <tx:method name="get*" read-only="true"/>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="count*" read-only="true"/>
        <tx:method name="*" />
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:pointcut expression="execution(* xx.xx.service.*.*(..))" id="txPointCut"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号