org.hibernate.HibernateException: No Session found for current thread

hibernate:4.1.6
spring:4.0.1

 

工程启动没错,进入getAllUser页面获得数据库用户信息时报如下错误: 

 

严重: Servlet.service() for servlet springMVC threw exception

org.hibernate.HibernateException: No Session found for current thread

at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)

at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)

at com.mlf.web.controller.dao.UserDAO.getAllUser(UserDAO.java:27)

at com.mlf.web.controller.service.UserManager.getAllUser(UserManager.java:28)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:597)

at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)

at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)

at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)

at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)

at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)

at $Proxy19.getAllUser(Unknown Source)

at com.mlf.web.controller.UserController.getAllUser(UserController.java:36)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

at java.lang.reflect.Method.invoke(Method.java:597)

at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)

at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)

at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)

at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)

at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)

at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)

at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)

at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)

at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149)

at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)

at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)

at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)

at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617)

at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760)

at java.lang.Thread.run(Thread.java:619)

-----------------------------------------------------------------------------------------------------------------------------------------

hibernate.cfg.test.xml(com.mlf.web.controller.hibernate)

 

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="com.mlf.web.controller.entity.User"/>
    </session-factory>
</hibernate-configuration>

 -----------------------------------------------------------------------------------------------------------------------------------------

 

applicationContext.xml(com.mlf.web.controller.spring)

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>

<beans>
    <bean id="userDao" class="com.mlf.web.controller.dao.UserDAO">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <bean id="userManagerBase" class="com.mlf.web.controller.service.UserManager">
        <property name="userDao" ref="userDao"></property>
    </bean>
    
    <bean id="userManager" parent="transactionBese">
        <property name="target" ref="userManagerBase"></property>
    </bean>
    
</beans>

  -----------------------------------------------------------------------------------------------------------------------------------------

 

spring-annotation.xml(包:config)

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
        
    <!-- 扫描包 -->
    <context:component-scan base-package="com.mlf.web.controller"></context:component-scan>
    
    <!-- 开启注解 -->
    <mvc:annotation-driven/>
    
    <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->
    
    <!-- 静态资源访问 -->
    <mvc:resources location="/img/" mapping="/img/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>


    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>   
    
    <!-- 配置文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 文件最大值 -->
        <property name="maxUploadSize" value="10485760000"/>
        <!-- 缓存大小 -->
        <property name="maxInMemorySize" value="40960"/>
    </bean>
        
</beans>

   -----------------------------------------------------------------------------------------------------------------------------------------

 

spring-core.xml(包:config)

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>

<beans>
    <import resource="classpath:com/mlf/web/controller/spring/applicationContext.xml"/>
</beans>

    -----------------------------------------------------------------------------------------------------------------------------------------

 

spring-hibernate.xml(包:config)

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>

<beans>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncodeing=utf-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="donny2014"></property>
    </bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
                <!-- 自动更新 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!-- 在控制台打印SQL语句 -->
                <prop key="hibernate.show_sql">true</prop>
                <!-- 将SQL脚本进行格式化后再输出 -->
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="configLocations">
            <list>
                <value>
                    classpath:com/mlf/web/controller/hibernate/hibernate.cfg.test.xml
                </value>
            </list>
        </property>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <!-- 配置事务 -->
    <bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
        <property name="transactionManager" ref="transactionManager"></property>
        <property name="transactionAttributes">
            <props>
                <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="get*">PROPAGATION_NEVER</prop>
            </props>
        </property>
    </bean>
    
</beans>

     -----------------------------------------------------------------------------------------------------------------------------------------

 

UserController.java(包:com.mlf.web.controller)

 

package com.mlf.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mlf.web.controller.entity.User;
import com.mlf.web.controller.service.IUserManager;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource(name="userManager")
    private IUserManager userManager;
    
    @RequestMapping("/toAddUser")
    public String toAddUser(){
        return "/addUser";
    }
    
    @RequestMapping("/addUser")
    public String addUser(User user){
        
        userManager.addUser(user);
        
        return "/success";
    }
    
    @RequestMapping("/getAllUser")
    public String getAllUser(HttpServletRequest request){
        List<User> user = userManager.getAllUser();
        
        request.setAttribute("user", user);
        
        return "/userManager";
    }
}

 

2个回答

没发userDao啊

在getAllUser方法上加Transactional注解

如果没有事务,刚开始的线程上下文是拿不到session的

mdd2012
墨籽迦 虽然没有解决问题,但非常感谢你的帮助。
大约 5 年之前 回复
mdd2012
墨籽迦 //IUserDAO package com.mlf.web.controller.dao; import java.util.List; import com.mlf.web.controller.entity.User; public interface IUserDAO { public void addUser(User user); public List<User> getAllUser(); }
大约 5 年之前 回复
mdd2012
墨籽迦 //userDAO package com.mlf.web.controller.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import com.mlf.web.controller.entity.User; public class UserDAO implements IUserDAO { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void addUser(User user) { sessionFactory.getCurrentSession().save(user); } @Override public List<User> getAllUser() { String hql = "from User"; Query query = sessionFactory.getCurrentSession().createQuery(hql); return query.list(); } }
大约 5 年之前 回复

把WEB XML发上来看看呗

forgetanything
forgetanything 配置TranactionManager并且通过@Transactional或者声明的方式配置的事务边界,那么Spring会在开始事务之前通过AOP的方式为当前线程创建Session,此时调用getCurrentSession()将得到正确结果
大约 5 年之前 回复
mdd2012
墨籽迦 发上来了。。
大约 5 年之前 回复
mdd2012
墨籽迦 问题补充里面只能打字
大约 5 年之前 回复
mdd2012
墨籽迦 WEB XML怎么发上来?
大约 5 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Spring事务总是报org.hibernate.HibernateException: No Session found for current thread
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>今天搞了一下spring mvc的注解,弄到数据库的时候,向数据库中存数据没办法存入成功,看一下错误代码是org.hibernate.HibernateException: No Session found for current thread,网上找了一些方法一直没解决,哪位帮忙看一下,代码如下 <br>applicationContext-db.xml代码: <br><br>&lt;?xml version="1.0" encoding="UTF-8"?&gt; <br>&lt;beans xmlns="http://www.springframework.org/schema/beans" <br>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" <br>xmlns:context="http://www.springframework.org/schema/context" <br>xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" <br>xmlns:aop="http://www.springframework.org/schema/aop" <br>xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd <br>http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd <br>http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd <br>http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd <br>http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd" <br>default-lazy-init="true"&gt; <br><br>&lt;bean id="druid_dataSource" class="com.alibaba.druid.pool.DruidDataSource" <br>init-method="init" destroy-method="close"&gt; <br>&lt;property name="url" value="jdbc:oracle:thin:@localhost:1521:local" /&gt; <br>&lt;property name="username" value="activity" /&gt; <br>&lt;property name="password" value="activitygc" /&gt; <br>&lt;property name="maxActive" value="20" /&gt; <br>&lt;property name="validationQuery" value="select * from dual" /&gt; <br>&lt;property name="testWhileIdle" value="true" /&gt; <br>&lt;/bean&gt; <br><br>&lt;bean id="sessionFactory" <br>class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; <br>&lt;property name="dataSource" ref="druid_dataSource" /&gt; <br>&lt;property name="packagesToScan" value="com.mvc.model*"&gt;&lt;/property&gt; <br>&lt;property name="hibernateProperties"&gt; <br>&lt;props&gt; <br>&lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.Oracle10gDialect&lt;/prop&gt; <br>&lt;prop key="show_sql"&gt;true&lt;/prop&gt; <br>&lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt; <br>&lt;prop key="hibernate.jdbc.batch_size"&gt;20&lt;/prop&gt; <br>&lt;!-- &lt;prop key="hibernate.current_session_context_class"&gt;org.springframework.orm.hibernate4.SpringSessionContext <br>&lt;/prop&gt; --&gt; <br>&lt;!-- &lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt;  --&gt; <br>&lt;/props&gt; <br>&lt;/property&gt; <br>&lt;/bean&gt; <br><br>&lt;!-- 开启AOP监听 只对当前配置文件有效 --&gt; <br>&lt;aop:aspectj-autoproxy expose-proxy="true" /&gt; <br><br>&lt;!-- 开启注解事务 只对当前配置文件有效 --&gt; <br>&lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; <br>&lt;bean id="txManager" <br>class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; <br>&lt;property name="sessionFactory" ref="sessionFactory" /&gt; <br>&lt;/bean&gt; <br>&lt;tx:advice id="txAdvice" transaction-manager="txManager"&gt; <br>&lt;tx:attributes&gt; <br>&lt;tx:method name="save*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="add*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="create*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="insert*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="update*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="merge*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="del*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="remove*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="put*" propagation="REQUIRED" /&gt; <br>&lt;tx:method name="use*" propagation="REQUIRED" /&gt; <br>&lt;!-- hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --&gt; <br>&lt;tx:method name="get*" propagation="REQUIRED" read-only="true" /&gt; <br>&lt;tx:method name="count*" propagation="REQUIRED" read-only="true" /&gt; <br>&lt;tx:method name="find*" propagation="REQUIRED" read-only="true" /&gt; <br>&lt;tx:method name="list*" propagation="REQUIRED" read-only="true" /&gt; <br>&lt;tx:method name="is*" propagation="REQUIRED" read-only="true" /&gt; <br>&lt;/tx:attributes&gt; <br>&lt;/tx:advice&gt; <br><br>&lt;aop:config expose-proxy="true" proxy-target-class="true"&gt; <br>&lt;!-- 只对数据层实施事务 --&gt; <br>&lt;aop:pointcut id="txPointcut" expression="execution(* com.mvc.dao..*.*(..))" /&gt; <br>&lt;aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /&gt; <br>&lt;/aop:config&gt; <br>&lt;!-- 扫描并自动装配 --&gt; <br>&lt;context:component-scan base-package="com.mvc.dao" /&gt; <br>&lt;context:component-scan base-package="com.mvc.service" /&gt; <br>&lt;/beans&gt; <br><br>spring-servlet.xml代码 <br>&lt;?xml version="1.0" encoding="UTF-8"?&gt; <br>&lt;beans xmlns="http://www.springframework.org/schema/beans" <br>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" <br>xmlns:context="http://www.springframework.org/schema/context" <br>xmlns:mvc="http://www.springframework.org/schema/mvc" <br>xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd <br>http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd <br>http://www.springframework.org/schema/mvc <br>http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd" <br>default-lazy-init="true"&gt; <br>&lt;!-- 启用spring mvc 注解 --&gt; <br>&lt;context:annotation-config /&gt; <br>&lt;!-- 把标记了@Controller注解的类转换为bean --&gt; <br>&lt;context:component-scan base-package="com.mvc.*" /&gt; <br>&lt;!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --&gt; <br>&lt;bean <br>class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&gt; <br>    &lt;bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt;   <br>        &lt;property name="order" value="0"&gt;&lt;/property&gt;   <br>     &lt;/bean&gt; <br>     &lt;!-- 启动 Spring MVC 的注解功能,完成请求和注解 POJO 的映射 --&gt;   <br>     &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt;   <br>        &lt;property name="messageConverters"&gt;   <br>            &lt;list&gt;   <br>                 &lt;bean class="org.springframework.http.converter.StringHttpMessageConverter" /&gt;   <br>             &lt;/list&gt;   <br>         &lt;/property&gt;   <br>     &lt;/bean&gt;   <br>     <br>&lt;!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --&gt; <br>&lt;bean <br>class="org.springframework.web.servlet.view.InternalResourceViewResolver" <br>p:prefix="/WEB-INF/test/" p:suffix=".jsp" /&gt; <br><br>&lt;bean id="multipartResolver" <br>class="org.springframework.web.multipart.commons.CommonsMultipartResolver" <br>p:defaultEncoding="utf-8" /&gt; <br>     &lt;/beans&gt;  <br>web.xml <br>&lt;?xml version="1.0" encoding="UTF-8"?&gt;  <br>&lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt;  <br>  &lt;display-name&gt;s3h3&lt;/display-name&gt;  <br>   &lt;context-param&gt;    <br>     &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;    <br>     &lt;param-value&gt;classpath:applicationContext*.xml&lt;/param-value&gt;    <br>&lt;/context-param&gt;    <br>&lt;listener&gt;    <br>    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;    <br>&lt;/listener&gt;    <br>  &lt;context-param&gt;   <br>        &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;   <br>        &lt;param-value&gt;/WEB-INF/log4j.properties&lt;/param-value&gt;   <br>     &lt;/context-param&gt; <br>&lt;servlet&gt;    <br>     &lt;servlet-name&gt;spring&lt;/servlet-name&gt;    <br>     &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;   <br>     &lt;init-param&gt; <br>&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; <br>&lt;param-value&gt;/WEB-INF/classes/spring-servlet.xml&lt;/param-value&gt; <br>&lt;/init-param&gt; <br>     &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;    <br>&lt;/servlet&gt;   <br>  &lt;filter&gt; <br>&lt;filter-name&gt;encoding&lt;/filter-name&gt; <br>&lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt; <br>&lt;init-param&gt; <br>&lt;param-name&gt;encoding&lt;/param-name&gt; <br>&lt;param-value&gt;utf-8&lt;/param-value&gt; <br>&lt;/init-param&gt; <br>&lt;/filter&gt; <br>&lt;filter-mapping&gt; <br>&lt;filter-name&gt;encoding&lt;/filter-name&gt; <br>&lt;url-pattern&gt;*.do&lt;/url-pattern&gt; <br>&lt;/filter-mapping&gt; <br>&lt;filter-mapping&gt; <br>&lt;filter-name&gt;encoding&lt;/filter-name&gt; <br>&lt;url-pattern&gt;*.jspx&lt;/url-pattern&gt; <br>&lt;/filter-mapping&gt; <br>&lt;filter-mapping&gt; <br>&lt;filter-name&gt;encoding&lt;/filter-name&gt; <br>&lt;url-pattern&gt;*.jhtml&lt;/url-pattern&gt; <br>&lt;/filter-mapping&gt; <br>&lt;filter-mapping&gt; <br>&lt;filter-name&gt;encoding&lt;/filter-name&gt; <br>&lt;url-pattern&gt;*.html&lt;/url-pattern&gt; <br>&lt;/filter-mapping&gt; <br>&lt;filter-mapping&gt; <br>&lt;filter-name&gt;encoding&lt;/filter-name&gt; <br>&lt;url-pattern&gt;*.htm&lt;/url-pattern&gt; <br>&lt;/filter-mapping&gt; <br>&lt;filter-mapping&gt; <br>&lt;filter-name&gt;encoding&lt;/filter-name&gt; <br>&lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; <br>&lt;/filter-mapping&gt; <br>&lt;servlet-mapping&gt;    <br>     &lt;servlet-name&gt;spring&lt;/servlet-name&gt; <br>     &lt;url-pattern&gt;*.do&lt;/url-pattern&gt;    <br>&lt;/servlet-mapping&gt;    <br>  &lt;welcome-file-list&gt;  <br>    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;  <br>  &lt;/welcome-file-list&gt;  <br>&lt;/web-app&gt; </p> <p> </p> </div>
使用spring3.X+Hibernate4.X来做项目,报异常 No Session found for current thread
org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941) at com.isoft.dao.impl.HibernateDaoImpl.getSession(HibernateDaoImpl.java:51) at com.isoft.dao.impl.HibernateDaoImpl.save(HibernateDaoImpl.java:77) at com.isoft.service.impl.BaseServiceImpl.save(BaseServiceImpl.java:42) at com.isoft.test.MessageInvoiceServiceImplTest.testAdd(MessageInvoiceServiceImplTest.java:53) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:300) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
class not found org.hibernate.dialect.SQLServerDialect
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in file [E:\JavaHome\EclipseSource\eclipse\spage\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\environment\WEB-INF\classes\config\spring-context.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.SQLServerDialect <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <value> hibernate.hbm2ddl.auto=create hibernate.show_sql=true hibernate.dialect=org.hibernate.dialect.SQLServerDialect hibernate.current_context_session_class=thread </value> </property> <property name="mappingResources"> <list> <value>xht/test/man/domain/Man.hbm.xml</value> </list> </property> </bean> 我已经看过了。。。 hibernate3 里面也有这个 .class 文件 数据库驱动的jar包 buildpath 里面也已经引入了! 网上查了也没什么具体原因。。。
spring3.2+hibernate4.2 整合 spring security报No Session found for current thread
[code="java"] public class SpringSecurityMetaDataSource implements FilterInvocationSecurityMetadataSource { //@Resource(name = "resourceDao") private ResourceDao resourceDao; private static Map<String, Collection<ConfigAttribute>> resourceMap = null; @Autowired public SpringSecurityMetaDataSource(ResourceDao resourceDao) { this.resourceDao = resourceDao; loadResourceDefine(); } } /** * 加载所有资源与权限的关系 */ @SuppressWarnings("unused") private void loadResourceDefine() { if(resourceMap == null) { resourceMap = new HashMap<String, Collection<ConfigAttribute>>(); List<ResourceManager> resources = this.resourceDao.listAll(ResourceManager.class); for (ResourceManager resource : resources) { Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>(); //以权限名封装为Spring的security Object ConfigAttribute configAttribute = new SecurityConfig(resource.getName()); configAttributes.add(configAttribute); resourceMap.put(resource.getUrl(), configAttributes); } } Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet(); Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator(); } [/code] 断点跟进去后发现: List<ResourceManager> resources = this.resourceDao.listAll(ResourceManager.class); 是这抛出的错,报Caused by: org.hibernate.HibernateException: No Session found for current thread 我怀疑 通过构造方法注入的resourceDao不受hibernate的事务管理, 因此上诉代码改为了: [code="java"] @Resource(name = "resourceDao") private ResourceDao resourceDao; private static Map<String, Collection<ConfigAttribute>> resourceMap = null; @Autowired public SpringSecurityMetaDataSource() { loadResourceDefine(); } [/code] 这样的话,又会报resourceDao为空指针错, 详见代码附件。 jar包如下: antlr-2.7.7.jar aopalliance-1.0.jar aspectjrt.jar aspectjweaver.jar commons-fileupload-1.3.jar commons-logging-1.1.2.jar dom4j-1.6.1.jar druid-0.2.12.jar hibernate-commons-annotations-4.0.1.Final.jar hibernate-core-4.2.0.Final.jar hibernate-jpa-2.0-api-1.0.1.Final.jar javassist-3.15.0-GA.jar jboss-logging-3.1.0.GA.jar jta-1.1.jar mysql-connector-java-5.1.21.jar spring-aop-3.2.2.RELEASE.jar spring-aspects-3.2.2.RELEASE.jar spring-beans-3.2.2.RELEASE.jar spring-context-3.2.2.RELEASE.jar spring-core-3.2.2.RELEASE.jar spring-expression-3.2.2.RELEASE.jar spring-jdbc-3.2.2.RELEASE.jar spring-orm-3.2.2.RELEASE.jar spring-security-config-3.2.0.M1.jar spring-security-core-3.2.0.M1.jar spring-security-web-3.2.0.M1.jar spring-tx-3.2.2.RELEASE.jar spring-web-3.2.2.RELEASE.jar spring-webmvc-3.2.2.RELEASE.jar
Spring整合hibernate4时出现no session错误
首先将eclipse抛出的错误贴出来: ``` 严重: Servlet.service() for servlet [springDispatcherServlet] in context with path [/VideoMngSys] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: No Session found for current thread] with root cause org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:988) at com.vincent.videosys.dao.BaseDao.getSession(BaseDao.java:17) at com.vincent.videosys.dao.UserDao.usernameExist(UserDao.java:29) at com.vincent.videosys.service.UserService.usernameExistService(UserService.java:19) at com.vincent.videosys.controller.home.UserController.usernameExist(UserController.java:40) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle (ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod (RequestMappingHandlerAdapter.java:748) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal (RequestMappingHandlerAdapter.java:689) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle (AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931) .... ``` ![项目工程结构如下:](https://img-ask.csdn.net/upload/201601/02/1451707793_69876.png) 下面依次贴出我的相关文件代码: 1.web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- 加载Spring配置文件,Spring应用上下文,理解层次化的ApplicationContext --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 可以将POST请求转为PUT请求和DELETE请求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app> ``` 2.spring-mvc.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" ......> <!-- 向Spring容器注册AutowiredAnnotationBeanPostProcessor、 CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor、 RequiredAnnotationBeanPostProcessor,使系统能识别注解 --> <context:annotation-config /> <!-- 使用annotation自动注册bean,并检查@Controller、@Service、@Repository --> <context:component-scan base-package="com.vincent.videosys"></context:component-scan> <!-- 导入资源文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置C3P0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="packagesToScan"> <list> <value>com.vincent.videosys.*</value> </list> </property> </bean> <!-- 配置hibernate的事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 定义AutoWired自动注入bean --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"></bean> <!-- 用注解来实现事务管理 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 --> <aop:config> <aop:pointcut expression="execution(* com.vincent.videosys.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> </beans> ``` 4.hibernate.cfg.xml ``` <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <!-- JDBC connection pool (use the built-in) --> <!-- <property name="connection.pool_size">1</property>--> <!-- 数据库使用的方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <!-- 设置 打印输出 sql 语句 为真 --> <property name="hibernate.show_sql">true</property> <!-- 设置格式为 sql --> <property name="hibernate.format_sql">true</property> <!-- 第一次加载 hibernate 时根据实体类自动建立表结构,以后自动更新表结构 --> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property> </session-factory> </hibernate-configuration> ``` 5.db.properties jdbc.user=root jdbc.password=root jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql://localhost:3306/videomngsys jdbc.initPoolSize=5 jdbc.maxPoolSize=10 6. BaseDao.java ``` package com.vincent.videosys.dao; import javax.annotation.Resource; ..... @Repository("baseDao") public class BaseDao{ @Autowired protected SessionFactory sessionFactory; public Session getSession(){ return this.sessionFactory.getCurrentSession(); } } ``` 7.UserDao.java ``` package com.vincent.videosys.dao; import org.hibernate.Query; import org.hibernate.Session; .... @Repository("userDao") public class UserDao extends BaseDao{ protected SessionFactory sessionFactory; /** * 查看该用户名在数据库中是否存在 * 存在返回true * 不存在返回false * 默认返回true * @param username * @return */ public boolean usernameExist(String username){ boolean exist = true; String hqlString = "from user where username = :username"; Session session = super.getSession(); Query query = session.createQuery(hqlString); query.setParameter("username", username); List<User> list = query.list(); if(list.size() > 0) { exist = false; } return exist; } } ``` 8 UserService.java ``` package com.vincent.videosys.service; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; ... @Transactional @Service("userService") public class UserService { @Autowired private UserDao userDao; public boolean usernameExistService(String username){ return userDao.usernameExist(username); } } ``` 9. UserController.java ``` package com.vincent.videosys.controller.home; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; ..... @RequestMapping("/user") @Controller public class UserController { @Autowired private UserService userService; @ResponseBody @RequestMapping(value="/usernameExist",method=RequestMethod.POST) public Map<String, String> usernameExist(@RequestParam("username")String usernameString ){ Map<String, String> resultMap = new HashMap<String, String>(); System.out.println("username: "+usernameString); if(userService.usernameExistService(usernameString)){ resultMap.put("status", "1");//exits } else{ resultMap.put("status", "0");//not exist } return resultMap; } } ``` 每次程序执行到UserController类中的userNameExist方法时,开始调用userService中的方法时,便开始抛出错误.....
hibernate4整合spring4的问题
org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:992) at com.dzm.dao.impl.UserDao.saveObject(UserDao.java:23) at com.dzm.dao.impl.UserDao$$FastClassByCGLIB$$cc8fbb79.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:713) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646) at com.dzm.dao.impl.UserDao$$EnhancerByCGLIB$$d4ef01f3.saveObject(<generated>) at com.dzm.serviceImpl.UserManagerImpl.regUser(UserManagerImpl.java:25) at com.dzm.action.RegisterAction.execute(RegisterAction.java:29) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:249) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:249) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2522) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2511) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source)
hibernate的sessionFactory的问题
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <pre name="code" class="错误信息">2014-8-8 17:29:19 org.hibernate.cfg.Environment &lt;clinit&gt; 信息: Hibernate 3.2.7 2014-8-8 17:29:19 org.hibernate.cfg.Environment &lt;clinit&gt; 信息: hibernate.properties not found 2014-8-8 17:29:19 org.hibernate.cfg.Environment buildBytecodeProvider 信息: Bytecode provider name : cglib 2014-8-8 17:29:19 org.hibernate.cfg.Environment &lt;clinit&gt; 信息: using JDK 1.4 java.sql.Timestamp handling 2014-8-8 17:29:19 org.hibernate.cfg.Configuration configure 信息: configuring from resource: /hibernate.cfg.xml 2014-8-8 17:29:19 org.hibernate.cfg.Configuration getConfigurationInputStream 信息: Configuration resource: /hibernate.cfg.xml 2014-8-8 17:29:19 org.hibernate.cfg.Configuration addResource 信息: Reading mappings from resource : com/bjsxt/hibernate/Student.hbm.xml 2014-8-8 17:29:20 org.hibernate.cfg.Configuration doConfigure 信息: Configured SessionFactory: null 2014-8-8 17:29:20 org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues 信息: Mapping class: com.bjsxt.hibernate.Student -&gt; Student 2014-8-8 17:29:20 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: Using Hibernate built-in connection pool (not for production use!) 2014-8-8 17:29:20 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: Hibernate connection pool size: 1 2014-8-8 17:29:20 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: autocommit mode: false 2014-8-8 17:29:20 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: using driver: oracle.jdbc.driver.OracleDriver at URL: jdbc:oracle:thin:@localhost:1521:orcl 2014-8-8 17:29:20 org.hibernate.connection.DriverManagerConnectionProvider configure 信息: connection properties: {user=machanglun, password=****} 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: RDBMS: Oracle, version: Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production With the Partitioning, OLAP, Data Mining and Real Application Testing options 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC driver: Oracle JDBC driver, version: 9.2.0.3.0 2014-8-8 17:29:21 org.hibernate.dialect.Dialect &lt;init&gt; 信息: Using dialect: org.hibernate.dialect.OracleDialect 2014-8-8 17:29:21 org.hibernate.dialect.Oracle9Dialect &lt;init&gt; 警告: The Oracle9Dialect dialect has been deprecated; use either Oracle9iDialect or Oracle10gDialect instead 2014-8-8 17:29:21 org.hibernate.dialect.OracleDialect &lt;init&gt; 警告: The OracleDialect dialect has been deprecated; use Oracle8iDialect instead 2014-8-8 17:29:21 org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory 信息: Using default transaction strategy (direct JDBC transactions) 2014-8-8 17:29:21 org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup 信息: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Automatic flush during beforeCompletion(): disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Automatic session close at end of transaction: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC batch size: 15 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC batch updates for versioned data: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Scrollable result sets: enabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: JDBC3 getGeneratedKeys(): disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Connection release mode: auto 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Default batch fetch size: 1 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Generate SQL with comments: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Order SQL updates by primary key: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Order SQL inserts for batching: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory 信息: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 2014-8-8 17:29:21 org.hibernate.hql.ast.ASTQueryTranslatorFactory &lt;init&gt; 信息: Using ASTQueryTranslatorFactory 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Query language substitutions: {} 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: JPA-QL strict compliance: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Second-level cache: enabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Query cache: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory createCacheProvider 信息: Cache provider: org.hibernate.cache.NoCacheProvider 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Optimize cache for minimal puts: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Structured second-level cache entries: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Echoing all SQL to stdout 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Statistics: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Deleted entity synthetic identifier rollback: disabled 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Default entity-mode: pojo 2014-8-8 17:29:21 org.hibernate.cfg.SettingsFactory buildSettings 信息: Named query checking : enabled 2014-8-8 17:29:21 org.hibernate.impl.SessionFactoryImpl &lt;init&gt; 信息: building session factory Exception in thread "main" org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer] at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:110) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:135) at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.&lt;init&gt;(EntityEntityModeToTuplizerMapping.java:56) at org.hibernate.tuple.entity.EntityMetamodel.&lt;init&gt;(EntityMetamodel.java:323) at org.hibernate.persister.entity.AbstractEntityPersister.&lt;init&gt;(AbstractEntityPersister.java:433) at org.hibernate.persister.entity.SingleTableEntityPersister.&lt;init&gt;(SingleTableEntityPersister.java:109) at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55) at org.hibernate.impl.SessionFactoryImpl.&lt;init&gt;(SessionFactoryImpl.java:231) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1313) at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867) at com.bjsxt.hibernate.TeacherTest.main(TeacherTest.java:14) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:107) ... 10 more Caused by: java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter at org.hibernate.bytecode.cglib.BytecodeProviderImpl.getProxyFactoryFactory(BytecodeProviderImpl.java:33) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactoryInternal(PojoEntityTuplizer.java:208) at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:186) at org.hibernate.tuple.entity.AbstractEntityTuplizer.&lt;init&gt;(AbstractEntityTuplizer.java:128) at org.hibernate.tuple.entity.PojoEntityTuplizer.&lt;init&gt;(PojoEntityTuplizer.java:78) ... 15 more Caused by: java.lang.ClassNotFoundException: net.sf.cglib.proxy.CallbackFilter at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) ... 20 more </pre> <p> </p> <pre name="code" class="hibernate.cfg.xml">&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;!-- Database connection settings --&gt; &lt;property name="connection.driver_class"&gt;oracle.jdbc.driver.OracleDriver&lt;/property&gt; &lt;property name="connection.url"&gt;jdbc:oracle:thin:@localhost:1521:orcl&lt;/property&gt; &lt;property name="connection.username"&gt;xxx&lt;/property&gt; &lt;property name="connection.password"&gt;xxx&lt;/property&gt; &lt;!-- JDBC connection pool (use the built-in) --&gt; &lt;property name="connection.pool_size"&gt;1&lt;/property&gt; &lt;!-- SQL dialect --&gt; &lt;property name="dialect"&gt;org.hibernate.dialect.OracleDialect&lt;/property&gt; &lt;!-- Enable Hibernate's automatic session context management --&gt; &lt;property name="current_session_context_class"&gt;thread&lt;/property&gt; &lt;!-- Disable the second-level cache --&gt; &lt;property name="cache.provider_class"&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt; &lt;!-- Echo all executed SQL to stdout --&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;!-- Drop and re-create the database schema on startup --&gt; &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt; &lt;mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/&gt; &lt;mapping class="com.bjsxt.hibernate.Teacher"/&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt;</pre> <p> </p> <pre name="code" class="Teacher.java">package com.bjsxt.hibernate; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Teacher { private int id; private String name; private String title; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } </pre> <p> </p> <pre name="code" class="TeacherTest">package com.bjsxt.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class TeacherTest { public static void main(String[] args) { Teacher t = new Teacher(); t.setId(1); t.setName("t1"); t.setTitle("middle"); SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); session.save(t); session.getTransaction().commit(); } } </pre> <p> </p> </div>
高手进,关于hibernate的
public void testAA2(){ HibernateUtil.beginTransaction(); Session session=HibernateUtil.getCurrentSession(); ClassRoom room=(ClassRoom)session.load(ClassRoom.class,new Integer(1)); Set<Student> set=room.getSet(); ClassRoom room1=new ClassRoom(); room1.setName("0002"); room1.setSet(set); Iterator iter=set.iterator(); while(iter.hasNext()){ Student student=(Student)iter.next(); student.setRoomid(room1); } session.save(room1); session.getTransaction().commit(); session.close(); } 这段程序出错了,怎么回事呀 org.hibernate.HibernateException: Found shared references to a collection: org.ldsj.pojo.ClassRoom.set at org.hibernate.engine.Collections.processReachableCollection(Collections.java:163) at org.hibernate.event.def.FlushVisitor.processCollection(FlushVisitor.java:37) at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101) at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61) at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55) at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:124) at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:195) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:985) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:333) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at org.ldsj.test.Test2.testAA2(Test2.java:58) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Spring3.2+Hibernate4.1集成的时候提示找不到Session
<p>大家好, 我今天在整合spring3+hibernate的时候老是被提示找不到session  我获取session的方式是sessionFactory.getCurrentSession()</p> <p>控制台报的错误:</p> <pre name="code" class="控制台消息">严重: Servlet.service() for servlet springmvc threw exception org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:978) at cn.ccsu.dao.impl.UserDaoImpl.getSession(UserDaoImpl.java:48) at cn.ccsu.dao.impl.UserDaoImpl.exist(UserDaoImpl.java:22) at cn.ccsu.manager.impl.UserManagerImpl.register(UserManagerImpl.java:20) at cn.ccsu.web.UserAction.register(UserAction.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:619) </pre> <p> applicationContext.xml文件</p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" default-autowire="byName"&gt; &lt;context:component-scan base-package="cn.ccsu" /&gt; &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;value&gt;classpath:config/jdbc.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"&gt; &lt;property name="driverClass" value="${hibernate.connection.driver_class}" /&gt; &lt;property name="jdbcUrl" value="${hibernate.connection.url}" /&gt; &lt;property name="user" value="${hibernate.connection.username}" /&gt; &lt;property name="password" value="${hibernate.connection.password}" /&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt; org.hibernate.dialect.MySQLDialect &lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.format_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.current_session_context_class"&gt;org.springframework.orm.hibernate4.SpringSessionContext&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="packagesToScan"&gt; &lt;value&gt;cn.ccsu.model&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt; &lt;/beans&gt;</pre> <p> web.xml文件</p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;display-name&gt;S3SH&lt;/display-name&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; classpath:config/applicationContext.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;filter&gt; &lt;filter-name&gt;OpenSessionInViewFilter&lt;/filter-name&gt; &lt;filter-class&gt; org.springframework.orm.hibernate4.support.OpenSessionInViewFilter &lt;/filter-class&gt; &lt;!-- 指定在spring配置的sessionFactory --&gt; &lt;init-param&gt; &lt;param-name&gt;sessionFactoryBeanName&lt;/param-name&gt; &lt;param-value&gt;mysqlSessionFactory&lt;/param-value&gt; &lt;/init-param&gt; &lt;!-- singleSession默认为true,若设为false则等于没用OpenSessionInView --&gt; &lt;init-param&gt; &lt;param-name&gt;singleSession&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;!-- 处理中文乱码问题 start --&gt; &lt;filter&gt; &lt;filter-name&gt;UTF-Encoding&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;encoding&lt;/param-name&gt; &lt;param-value&gt;UTF-8&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;forceEncoding&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;UTF-Encoding&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- 处理中文乱码问题 end --&gt; &lt;!-- springmvc start --&gt; &lt;servlet&gt; &lt;servlet-name&gt;springmvc&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath:config/springmvc-servlet.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;springmvc&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- springmvc end --&gt; &lt;/web-app&gt;</pre> <p> UserManagerImpl.java</p> <pre name="code" class="java">package cn.ccsu.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import cn.ccsu.dao.UserDao; import cn.ccsu.model.UserBean; @SuppressWarnings("unchecked") @Component("userDao") public class UserDaoImpl implements UserDao { @Override public boolean exist(UserBean userBean) { String hql = "from UserBean userBean where userBean.username=:key"; Query q = getSession().createQuery(hql); q.setParameter("key", userBean.getUsername()); if (q.list().size() &gt; 0) { return true; } return false; } @Override public UserBean addUser(UserBean userBean) { getSession().save(userBean); return userBean; } @Override public List&lt;UserBean&gt; getAllUserList() { return getSession().createQuery("from UserBean").list(); } @Autowired @Qualifier("sessionFactory") private SessionFactory sessionFactory; public Session getSession() { return sessionFactory.getCurrentSession(); } } </pre> <p> 以上就是这个项目的主要代码了 请各位大神帮我瞧瞧  多谢</p>
hibernate4.1 创建session 求助!
**我的测试类** package test; import org.hibernate.*; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import com.computer.cs.entity.Users; public class Test { private SessionFactory sessionFactory; private Session session; private Transaction transaction; public void init(){ Configuration config = new Configuration().configure(); //创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); sessionFactory=config.buildSessionFactory(serviceRegistry); session=sessionFactory.openSession(); transaction=session.beginTransaction(); } public void destory(){ transaction.commit(); session.close(); sessionFactory.close(); } public void test(){ Users u = new Users("ee","1234567",(short)1,322); session.save(u); } public static void main(String[] args) { Test t1 = new Test(); t1.init(); t1.test(); t1.destory(); } } **下面是报错** log4j:WARN No appenders could be found for logger (org.jboss.logging). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173) at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1947) at org.hibernate.cfg.Configuration.configure(Configuration.java:1928) at org.hibernate.cfg.Configuration.configure(Configuration.java:1908) at test.Test.init(Test.java:18) at test.Test.main(Test.java:40) **hibernate配置文档** <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.url"> jdbc:mysql://127.0.0.1:3306/csdatabase </property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="myeclipse.connection.profile"> CSdatabase </property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping resource="com/computer/cs/entity/Users.hbm.xml" /> <mapping resource="com/computer/cs/entity/Inexp.hbm.xml" /> <mapping resource="com/computer/cs/entity/Project.hbm.xml" /> </session-factory> </hibernate-configuration> ![图片说明](https://img-ask.csdn.net/upload/201811/28/1543347724_772277.png) 初学框架,现在真的是一脸懵逼
问下各位大神,我刚学Hibernate,下载是我的第一个代码,为什么老链接报错,希望大神们解答一下
1.持久化类代码: package Model; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; //开发持久化类 public class Connec_Base { private SessionFactory sessionFactory; private Session session; private Transaction trancaction; private Configuration conf; private ServiceRegistry serviceRegister; public void init(){ //创建配置对象 try { conf = new Configuration().configure(); } catch (HibernateException e) { System.out.println("创建配置对象失败"); e.printStackTrace(); } //创建服务注册对象 try { // serviceRegister = new StandardServiceRegistryBuilder(). // applySettings(conf.getProperties()).build(); serviceRegister=new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry(); } catch (Exception e) { System.out.println("创建服务注册对象失败"); e.printStackTrace(); } System.out.println(serviceRegister); try { //创建会话工厂对象 sessionFactory=conf.buildSessionFactory(serviceRegister); } catch (HibernateException e) { System.out.println("创建会话工厂对象失败"); e.printStackTrace(); } //会话对象 session=sessionFactory.openSession(); //开启事物 trancaction=session.beginTransaction(); } public void Destory(){ //开启事物 trancaction.commit(); //关闭会话 session.close(); //关闭会话工厂 sessionFactory.close(); } public void add(Student s){ init(); session.save(s); Destory(); } } 2.hibernate.cfg.xml代码: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/text?useUnicode=true&amp;characterEncoding=UTF-8</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">ch2738</property> <!-- 显示sql语句 --> <property name="hibernate.show_sql">true</property> <!-- 自动创建表格 --> <property name="hibernate.hbm2ddl.auto">true</property> <!-- 方言:为每一种数据库提供适配器,方便转换 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="Model/Student.hbm.xml"/> </session-factory> </hibernate-configuration> 3.Student.hbm.xml代码 <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated 2016-10-19 21:31:10 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="Student" table="STUDENT"> <id name="id" type="java.lang.String"> <column name="ID" /> <generator class="assigned" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="school" type="java.lang.String"> <column name="SCHOOL" /> </property> </class> </hibernate-mapping> ![代码结构图](https://img-ask.csdn.net/upload/201610/19/1476887581_62092.png) 3报错信息 十月 19, 2016 10:34:49 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final} 十月 19, 2016 10:34:49 下午 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {4.3.11.Final} 十月 19, 2016 10:34:49 下午 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 十月 19, 2016 10:34:49 下午 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 十月 19, 2016 10:34:49 下午 org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml 十月 19, 2016 10:34:49 下午 org.hibernate.cfg.Configuration getConfigurationInputStream INFO: HHH000040: Configuration resource: /hibernate.cfg.xml 十月 19, 2016 10:34:49 下午 org.hibernate.cfg.Configuration addResource INFO: HHH000221: Reading mappings from resource: Model/Student.hbm.xml 十月 19, 2016 10:34:50 下午 org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide! 十月 19, 2016 10:34:50 下午 org.hibernate.cfg.Configuration doConfigure INFO: HHH000041: Configured SessionFactory: null org.hibernate.boot.registry.internal.StandardServiceRegistryImpl@184f6be2 十月 19, 2016 10:34:50 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!) 十月 19, 2016 10:34:50 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://127.0.0.1:3306/text?useUnicode=true&characterEncoding=UTF-8] 十月 19, 2016 10:34:50 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000046: Connection properties: {user=root, password=****} 十月 19, 2016 10:34:50 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH000006: Autocommit mode: false 十月 19, 2016 10:34:50 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure INFO: HHH000115: Hibernate connection pool size: 20 (min=1) 创建会话工厂对象失败 org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:122) at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140) at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58) at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75) at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845) at Model.Connec_Base.init(Connec_Base.java:38) at Model.Connec_Base.add(Connec_Base.java:59) at Model.text.main(text.java:7) Caused by: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:943) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4113) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1308) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2336) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2369) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2153) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305) at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55) ... 15 more Exception in thread "main" java.lang.NullPointerException at Model.Connec_Base.init(Connec_Base.java:44) at Model.Connec_Base.add(Connec_Base.java:59) at Model.text.main(text.java:7)
spring3与hibernate4整合session问题
[color=red][b]问题描述:[/b][/color] 整合spring3与hibernate4时,发生错误:[u]nested exception is org.hibernate.HibernateException: No Session found for current thread[/u] 之后查找资料,添加[u]:<prop key="hibernate.current_session_context_class">thread</prop>[/u]属性,报错:org.hibernate.HibernateException: createQuery is not valid without active transaction, 查找资料说,删除上面我添加的那个属性,我被陷入死循环了。 [color=red][b]代码如下[/b][/color] [b]配置文件:[/b] [code="java"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:config/jdbc.properties</value> </list> </property> </bean> <!--数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${mysql.driver}</value> </property> <property name="jdbcUrl"> <value>${mysql.url}</value> </property> <property name="user"> <value>${mysql.userName}</value> </property> <property name="password"> <value>${mysql.password}</value> </property> <property name="acquireIncrement"> <value>${c3p0.acquireIncrement}</value> </property> <property name="initialPoolSize"> <value>${c3p0.initialPoolSize}</value> </property> <property name="minPoolSize"> <value>${c3p0.minPoolSize}</value> </property> <property name="maxPoolSize"> <value>${c3p0.maxPoolSize}</value> </property> <property name="maxIdleTime"> <value>${c3p0.maxIdleTime}</value> </property> <property name="idleConnectionTestPeriod"> <value>${c3p0.idleConnectionTestPeriod}</value> </property> <property name="maxStatements"> <value>${c3p0.maxStatements}</value> </property> <property name="numHelperThreads"> <value>${c3p0.numHelperThreads}</value> </property> <property name="testConnectionOnCheckout"> <value>${c3p0.testConnectionOnCheckout}</value> </property> <property name="preferredTestQuery"> <value>${c3p0.preferredTestQuery}</value> </property> </bean> <!-- Session 工厂配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com..entity</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <!-- 解决no session found --> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置事物管理器,在*ServiceImpl里写@Transactional就可以启用事物管理 --> <tx:annotation-driven transaction-manager="transactionManager" /> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 方法对应的传播属性 --> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED"/> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <!-- 事务控制位置,一般在业务层service --> <aop:config> <aop:pointcut id="txPointcut" expression="execution(* com..service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> </beans> [/code] [b]DAO[/b] [code="java"] package com.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; public class BaseDao { @Autowired private SessionFactory sessionFactory; public Session getCurrentSession() { return sessionFactory.getCurrentSession(); } } [/code] [code="java"] package com.test.dao.impl; import java.util.List; import org.hibernate.Query; import org.springframework.stereotype.Repository; import com.test.BaseDao; import com.test.dao.IUserDao; import com.test.entity.User; @Repository public class UserDaoImpl extends BaseDao implements IUserDao{ @SuppressWarnings("unchecked") @Override public List<User> findAllUsers() { String hql = "FROM User"; Query query = getCurrentSession().createQuery(hql); return query.list(); } } [/code] 各层次的ioc都OK的,问题出在哪里,或者解答下原因也可以,我自己查找资料,谢谢了。
关于一个webservice调用的错误
当我调用webservice开放的接口时 出现以下错误 ![图片说明](https://img-ask.csdn.net/upload/201509/15/1442318280_379860.png) log4j:WARN No appenders could be found for logger (com.allimu.webapp.UserLoginController). log4j:WARN Please initialize the log4j system properly. org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63) at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687) at com.allimu.dao.impl.BaseDAOImpl.getSession(BaseDAOImpl.java:40) at com.allimu.dao.impl.BaseDAOImpl.getObject(BaseDAOImpl.java:165) at com.allimu.service.impl.UserServiceImpl.getUserByPrams(UserServiceImpl.java:163) at com.allimu.auth.impl.ProxyAuthServiceImpl.proxyLogin(ProxyAuthServiceImpl.java:66) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.remoting.support.RemoteInvocationTraceInterceptor.invoke(RemoteInvocationTraceInterceptor.java:77) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy19.proxyLogin(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.caucho.hessian.server.HessianSkeleton.invoke(HessianSkeleton.java:306) at com.caucho.hessian.server.HessianSkeleton.invoke(HessianSkeleton.java:221) at org.springframework.remoting.caucho.HessianExporter.doInvoke(HessianExporter.java:198) at org.springframework.remoting.caucho.HessianExporter.invoke(HessianExporter.java:118) at org.springframework.remoting.caucho.HessianServiceExporter.handleRequest(HessianServiceExporter.java:66) at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:49) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:198) at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:176) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) 求解,求知。。
springMVC spring3.1 hibernate4 cxf整合发布restful风格的webservice
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>现在的问题是通过controller访问service是正常的,用cxf发布的webservice  就不访问不了service,报错:</p> <p><span style="color: #ff0000;">org.apache.cxf.interceptor.Fault: No Session found for current thread</span></p> <p>at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162)</p> <p>at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128)</p> <p>at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)</p> <p>at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)</p> <p>at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)</p> <p>at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:94)</p> <p>at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)</p> <p>at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)</p> <p>at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)</p> <p>at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)</p> <p>at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)</p> <p>at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:130)</p> <p>at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:221)</p> <p>at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:146)</p> <p>at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)</p> <p>at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:197)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)</p> <p>at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)</p> <p>at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)</p> <p>at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)</p> <p>at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)</p> <p>at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)</p> <p>at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)</p> <p>at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)</p> <p>at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)</p> <p>at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)</p> <p>at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)</p> <p>at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)</p> <p>at java.lang.Thread.run(Thread.java:662)</p> <p><span style="color: #ff0000;">Caused by: org.hibernate.HibernateException: No Session found for current thread</span></p> <p>at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)</p> <p>at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)</p> <p>at com.tservice.gisnavi.dao.impl.BaseDaoImpl.getCurrentSession(BaseDaoImpl.java:152)</p> <p>at com.tservice.gisnavi.dao.impl.BaseDaoImpl.find(BaseDaoImpl.java:186)</p> <p>at com.tservice.gisnavi.service.impl.RoutingCalculationServiceImpl.find(RoutingCalculationServiceImpl.java:14)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)</p> <p>--------------------------------------------------------------------------------------------------------------------------------------------------------------------</p> <p>spring-hibernate.xml配置:</p> <p>&lt;!-- 配置数据源 --&gt;</p> <p>&lt;bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"&gt;</p> <p>&lt;property name="url" value="${jdbc_url}" /&gt;</p> <p>&lt;property name="username" value="${jdbc_username}" /&gt;</p> <p>&lt;property name="password" value="${jdbc_password}" /&gt;</p> <p> </p> <p>&lt;!-- 初始化连接大小 --&gt;</p> <p>&lt;property name="initialSize" value="0" /&gt;</p> <p>&lt;!-- 连接池最大使用连接数量 --&gt;</p> <p>&lt;property name="maxActive" value="20" /&gt;</p> <p>&lt;!-- 连接池最大空闲 --&gt;</p> <p>&lt;property name="maxIdle" value="20" /&gt;</p> <p>&lt;!-- 连接池最小空闲 --&gt;</p> <p>&lt;property name="minIdle" value="0" /&gt;</p> <p>&lt;!-- 获取连接最大等待时间 --&gt;</p> <p>&lt;property name="maxWait" value="60000" /&gt;</p> <p> </p> <p>&lt;!-- &lt;property name="poolPreparedStatements" value="true" /&gt; &lt;property name="maxPoolPreparedStatementPerConnectionSize" value="33" /&gt; --&gt;</p> <p> </p> <p>&lt;property name="validationQuery" value="${validationQuery}" /&gt;</p> <p>&lt;property name="testOnBorrow" value="false" /&gt;</p> <p>&lt;property name="testOnReturn" value="false" /&gt;</p> <p>&lt;property name="testWhileIdle" value="true" /&gt;</p> <p> </p> <p>&lt;!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --&gt;</p> <p>&lt;property name="timeBetweenEvictionRunsMillis" value="60000" /&gt;</p> <p>&lt;!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --&gt;</p> <p>&lt;property name="minEvictableIdleTimeMillis" value="25200000" /&gt;</p> <p> </p> <p>&lt;!-- 打开removeAbandoned功能 --&gt;</p> <p>&lt;property name="removeAbandoned" value="true" /&gt;</p> <p>&lt;!-- 1800秒,也就是30分钟 --&gt;</p> <p>&lt;property name="removeAbandonedTimeout" value="1800" /&gt;</p> <p>&lt;!-- 关闭abanded连接时输出错误日志 --&gt;</p> <p>&lt;property name="logAbandoned" value="true" /&gt;</p> <p> </p> <p>&lt;!-- 监控数据库 --&gt;</p> <p>&lt;!-- &lt;property name="filters" value="stat" /&gt; --&gt;</p> <p>&lt;property name="filters" value="mergeStat" /&gt;</p> <p>&lt;/bean&gt;</p> <p> </p> <p>&lt;!-- 配置hibernate session工厂 --&gt;</p> <p>&lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;</p> <p>&lt;property name="dataSource" ref="dataSource" /&gt;</p> <p>&lt;property name="hibernateProperties"&gt;</p> <p>&lt;props&gt;</p> <p>&lt;prop key="hibernate.hbm2ddl.auto"&gt;${hibernate.hbm2ddl.auto}&lt;/prop&gt;</p> <p>&lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt;</p> <p>&lt;prop key="hibernate.show_sql"&gt;${hibernate.show_sql}&lt;/prop&gt;</p> <p>&lt;prop key="hibernate.format_sql"&gt;${hibernate.format_sql}&lt;/prop&gt;</p> <p>&lt;/props&gt;</p> <p>&lt;/property&gt;</p> <p> </p> <p>&lt;!-- 自动扫描注解方式配置的hibernate类文件 --&gt;</p> <p>&lt;property name="packagesToScan"&gt;</p> <p>&lt;list&gt;</p> <p>&lt;value&gt;com.tservice.gisnavi&lt;/value&gt;</p> <p>&lt;/list&gt;</p> <p>&lt;/property&gt;</p> <p> </p> <p>&lt;!-- 自动扫描hbm方式配置的hibernate文件和.hbm文件 --&gt;</p> <p>&lt;!-- </p> <p>&lt;property name="mappingDirectoryLocations"&gt;</p> <p>&lt;list&gt;</p> <p>&lt;value&gt;classpath:sy/hbm&lt;/value&gt;</p> <p>&lt;/list&gt;</p> <p>&lt;/property&gt;</p> <p>--&gt;</p> <p>&lt;/bean&gt;</p> <p> </p> <p>&lt;!-- 配置事务管理器 --&gt;</p> <p>&lt;bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;</p> <p>&lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt;</p> <p>&lt;/bean&gt;</p> <p> </p> <p>&lt;!-- &lt;aop:aspectj-autoproxy expose-proxy="true"/&gt; --&gt;</p> <p> </p> <p>&lt;!-- 注解方式配置事物 --&gt;</p> <p>&lt;!-- &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; --&gt;</p> <p> </p> <p>&lt;!-- 拦截器方式配置事物 --&gt;</p> <p>&lt;tx:advice id="transactionAdvice" transaction-manager="transactionManager"&gt;</p> <p>&lt;tx:attributes&gt;</p> <p>&lt;tx:method name="add*" /&gt;</p> <p>&lt;tx:method name="save*" /&gt;</p> <p>&lt;tx:method name="update*" /&gt;</p> <p>&lt;tx:method name="modify*" /&gt;</p> <p>&lt;tx:method name="edit*" /&gt;</p> <p>&lt;tx:method name="delete*" /&gt;</p> <p>&lt;tx:method name="remove*" /&gt;</p> <p>&lt;tx:method name="repair" /&gt;</p> <p>&lt;tx:method name="deleteAndRepair" /&gt;</p> <p> </p> <p>&lt;tx:method name="get*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="find*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="load*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="search*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="datagrid*" propagation="SUPPORTS" /&gt;</p> <p> </p> <p>&lt;tx:method name="*" propagation="SUPPORTS" /&gt;</p> <p>&lt;/tx:attributes&gt;</p> <p>&lt;/tx:advice&gt;</p> <p> </p> <p>&lt;aop:config&gt;</p> <p>&lt;aop:pointcut id="transactionPointcut" expression="execution(* com.tservice.gisnavi.service..*.*(..))" /&gt;</p> <p>&lt;aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /&gt;</p> <p>&lt;/aop:config&gt;</p> <p> </p> <p>&lt;/beans&gt;</p> <p> </p> <p> </p> <p> </p> </div>
Hibernate获取session问题
今天无意中发现用hibernate整合struts2,当app启动的时候session无法获取,报出了org.hibernate.HibernateException: JDBC Driver class not found: oracle.jdbc.driver.OracleDriver 这个错误,但是我的WEBINF中的lib目录里面确实存在oracle的classes12的工具包,而且当我在dao里面写一个测试方法单独运行java程序的时候,可以获取到session,为什么通过web启动的时候是空指针啊??高手大大们麻烦解析下
hibernate未初始化
package com.jady.test; import java.util.HashSet; import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test; import com.jady.domain.Dept; import com.jady.domain.Emp; import com.jady.domain.HibernateSessionFactory; public class TestEmpDept { @Test public void test(){ Session session = null; Transaction tx = null; try { session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); Dept dept = new Dept(); dept.setName("财务"); Emp e1 = new Emp(); e1.setName("tom"); Emp e2 = new Emp(); e2.setName("jerry"); // // // //关系 e1.setDept(dept); e2.setDept(dept); // Set<Emp> emps = new HashSet<Emp>(); emps.add(e1); emps.add(e2); // dept.setEmps(emps); // // //保存 // session.save(dept); // session.save(e1); // session.save(e2); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); tx.rollback(); }finally{ HibernateSessionFactory.closeSession(); } } } HibernateSessionFactory是用MyEclipse自动添加的,运行报错如下: java.lang.NoClassDefFoundError: Could not initialize class com.jady.domain.HibernateSessionFactory at com.jady.test.TestEmpDept.test(TestEmpDept.java:62) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:73) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:46) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41) at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.junit.runners.ParentRunner.run(ParentRunner.java:220) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) INFO Environment:514 - Hibernate 3.2.5 INFO Environment:547 - hibernate.properties not found INFO Environment:681 - Bytecode provider name : cglib INFO Environment:598 - using JDK 1.4 java.sql.Timestamp handling INFO Configuration:1426 - configuring from resource: /hibernate.cfg.xml INFO Configuration:1403 - Configuration resource: /hibernate.cfg.xml INFO Configuration:553 - Reading mappings from resource : com/jady/domain/Emp.hbm.xml INFO HbmBinder:300 - Mapping class: com.jady.domain.Emp -> Emp INFO Configuration:553 - Reading mappings from resource : com/jady/domain/Dept.hbm.xml INFO HbmBinder:300 - Mapping class: com.Jady.domain.Dept -> Dept
spring3 + hibernate 4.1 配置的问题
项目用:spring MVC + spring 3.2.4 + Hibernate 4.2.6+spring security3.1.4 在启动容器时,spring security 通过hibernate去数据库加载权限时,报:No Session found for current thread异常。 异常如下: [code="java"] Caused by: org.hibernate.HibernateException: No Session found for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:990) at com.seveng.weixin.foundation.dao.support.HibernateGenericDao.getSession(HibernateGenericDao.java:58) at com.seveng.weixin.foundation.dao.support.HibernateGenericDao.getAll(HibernateGenericDao.java:85) at com.seveng.weixin.foundation.security.filter.support.WeixinInvocationSecurityMetadataSourceService.loadResourceDefine(WeixinInvocationSecurityMetadataSourceService.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:344) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:295) at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130) ... 60 more [/code] spring MVC 配置文件:spring-mvc.xml [code="xml"] <mvc:annotation-driven /> <!-- 开启controller注解支持 --> <context:component-scan base-package="com.seveng.weixin" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> [/code] spring 主配置文件: [code="xml"] <context:component-scan base-package="com.seveng.weixin"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> [/code] 事务的配置: [code="xml"] <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <!-- 对业务逻辑层实施事务 --> <aop:pointcut id="txPointcut" expression="execution(* com.seveng.weixin..service.impl.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> <aop:aspectj-autoproxy expose-proxy="true"/> <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" /> [/code] 数据库数相关配置: [code="xml"] <!-- 加载资源文件 --> <context:property-placeholder location="classpath:config/database.properties" /> <!-- 数据库映射 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${connection.driver_class}" /> <property name="url" value="${connection.url}" /> <property name="username" value="${connection.username}" /> <property name="password" value="${connection.password}" /> </bean> <!-- hibernate 需要的信息 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com.seveng.weixin.**.model.*</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop> <prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop> <prop key="hibernate.max_fetch_depth">${hibernate.max_fetch_depth}</prop> <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop> <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.bytecode.use_reflection_optimizer}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> <prop key="hibernate.cache.use_structured_entries">${hibernate.cache.use_structured_entries}</prop> <prop key="net.sf.ehcache.configurationResourceName">${net.sf.ehcache.configurationResourceName}</prop> <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop> </props> </property> </bean> [/code] spring security 相关配置: [code="xml"] <!-- 不拦截的请求 --> <security:http pattern="/login" security="none" /> <security:http pattern="/images/**" security="none" /> <security:http pattern="/css/**" security="none" /> <security:http pattern="/js/**" security="none" /> <!-- 保护应用程序的所有URL --> <security:http auto-config="true"> <!-- login-page: 指定登录页面 --> <security:form-login login-page="/login" /> <security:logout logout-success-url="/login" /> <!-- 会话管理配置 ,设置最多登录一次,二次登录会让第一次登录失效, 则设置error-if-maximum-exceeded为false,要求第一次有效设置为true --> <security:session-management invalid-session-url="/login"> <security:concurrency-control max-sessions="1" error-if-maximum-exceeded="false" /> </security:session-management> <!-- 增加一个自定义的filter,放在FILTER_SECURITY_INTERCEPTOR之前, 实现用户、角色、权限、资源的数据库管理。 --> <security:custom-filter ref="weixinFilter" before="FILTER_SECURITY_INTERCEPTOR" /> </security:http> <!-- 一个自定义的filter,必须包含authenticationManager, accessDecisionManager,securityMetadataSource三个属性。 --> <bean id="weixinFilter" class="com.seveng.weixin.foundation.security.filter.WeixinFilterSecurityInterceptor"> <property name="authenticationManager" ref="authenticationManager" /> <property name="accessDecisionManager" ref="weixinAccessDecisionManager" /> <property name="securityMetadataSource" ref="weixinInvocationSecurityMetadataSourceService" /> </bean> <!-- 注意能够为authentication-manager 设置alias别名 --> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref="appUserDetailsService"> <security:password-encoder ref="passwordEncoder"> <security:salt-source user-property="username" /> </security:password-encoder> </security:authentication-provider> </security:authentication-manager> <!-- 事件监听:实现了 ApplicationListener监听接口,包括AuthenticationCredentialsNotFoundEvent 事件, AuthorizationFailureEvent事件,AuthorizedEvent事件, PublicInvocationEvent事件 --> <bean class="org.springframework.security.authentication.event.LoggerListener" /> <!-- 用户的密码加密或解密 --> <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" /> <!-- 启用用户的缓存功能 --> <bean id="userCache" class="org.springframework.security.core.userdetails.cache.EhCacheBasedUserCache"> <property name="cache" ref="userEhCache" /> </bean> <bean id="userEhCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheName" value="userCache" /> <property name="cacheManager" ref="cacheManager" /> </bean> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" > <property name="configLocation" value="classpath:config/ehcache.xml" /> </bean> [/code] 当容器启动时,spring security加载权限的代码 [code="java"] @PostConstruct @Transactional public void loadResourceDefine() { List<Authority> authorities = this.getAll(Authority.class); // 应当是资源为key, 权限为value。 资源通常为url, 权限就是那些以ROLE_为前缀的角色。 一个资源可以由多个权限来访问。 resourceMap = new HashMap<String, Collection<ConfigAttribute>>(); for (Authority auth : authorities) { ConfigAttribute ca = new SecurityConfig(auth.getAuthName()); Set<Resource> resources = auth.getResources(); for (Resource res : resources) { String url = res.getResString(); // 判断资源文件和权限的对应关系,如果已经存在相关的资源url,则要通过该url为key提取出权限集合,将权限增加到权限集合中 if (resourceMap.containsKey(url)) { Collection<ConfigAttribute> value = resourceMap.get(url); value.add(ca); resourceMap.put(url, value); } else { Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>(); atts.add(ca); resourceMap.put(url, atts); } } } } [/code]
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、PDF搜索网站推荐 对于大部
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
Vue + Spring Boot 项目实战(十四):用户认证方案与完善的访问拦截
本篇文章主要讲解 token、session 等用户认证方案的区别并分析常见误区,以及如何通过前后端的配合实现完善的访问拦截,为下一步权限控制的实现打下基础。
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入  假设现有4个人
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
漫话:什么是平衡(AVL)树?这应该是把AVL树讲的最好的文章了
这篇文章通过对话的形式,由浅入深带你读懂 AVL 树,看完让你保证理解 AVL 树的各种操作,如果觉得不错,别吝啬你的赞哦。 1、若它的左子树不为空,则左子树上所有的节点值都小于它的根节点值。 2、若它的右子树不为空,则右子树上所有的节点值均大于它的根节点值。 3、它的左右子树也分别可以充当为二叉查找树。 例如: 例如,我现在想要查找数值为14的节点。由于二叉查找树的特性,我们可...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
开源并不是你认为的那些事
点击上方蓝字 关注我们开源之道导读所以 ————想要理清开源是什么?先要厘清开源不是什么,名正言顺是句中国的古代成语,概念本身的理解非常之重要。大部分生物多样性的起源,...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
      11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下
《C++ Primer》学习笔记(六):C++模块设计——函数
专栏C++学习笔记 《C++ Primer》学习笔记/习题答案 总目录 https://blog.csdn.net/TeFuirnever/article/details/100700212 —————————————————————————————————————————————————————— 《C++ Primer》习题参考答案:第6章 - C++模块设计——函数 文章目录专栏C+...
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法不过,当我看了源代码之后这程序不到50
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
MySQL数据库总结
文章目录一、数据库简介二、MySQL数据类型(5.5版本)三、Sql语句(1)Sql语句简介(2)数据定义语言DDLcreate,alter,drop(3)数据操纵语言DMLupdate,insert,delete(4)数据控制语言DCLgrant,revoke(5)数据查询语言DQLselect(6)分组查询与分页查询group by,limit四、完整性约束(单表)五、多表查询六、MySQL数
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片
相关热词 如何提升c#开发能力 矩阵乘法c# c#调用谷歌浏览器 c# 去空格去转义符 c#用户登录窗体代码 c# 流 c# linux 可视化 c# mvc 返回图片 c# 像素空间 c# 日期 最后一天
立即提问