ssh 使用hibernateTemplate查询数据库里的内容一直是空指针

图片说明
下面是我的代码,求教各位大神

 public class PostsDaoImp extends HibernateDaoSupport implements PostsDao {

    public List<Posts> searchAllPosts() {
        List<Posts> list=null;
        try{
            list=(List)this.getHibernateTemplate().find("from Posts");
            if(list!=null||list.size()>0){
                return list;
            }else{
                return null;
            }
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
 public class PostsServiceImp implements PostsService{

    public PostsDao postDao;

    public PostsDao getPostDao() {
        return postDao;
    }

    public void setPostDao(PostsDao postDao) {
        this.postDao = postDao;
    }

    public List<Posts> searchAllPosts(){
        System.out.println("BBBBBBB");
        return postDao.searchAllPosts();
    }

}
 <!-- 配置数据访问层 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
            <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <bean id="pdi" class="com.shaolin.daoImp.PostsDaoImp">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 配置服务层 -->

    <bean id="postService" class="com.shaolin.service.PostsServiceImp">
        <property name="postDao" ref="pdi"></property>
    </bean>

    <!-- 配置Action曾 -->
    <bean id="postAction" class="com.shaolin.action.PostAction" scope="prototype">
        <property name="postsService" ref="postService"></property>
    </bean>
    <package name="post" extends="struts-default">
        <action name="post">
            <result name="opersuccess">/index.jsp</result>
        </action>
    </package>

3个回答

到底是hibernateTemplate为空还是查询出来的内容为空

额,谢谢,我已经找到问题了,我Struts.xml里少写了一个东西

strust里面少写了什么东西呀

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
使用ssh框架做新增功能时无法将数据写入数据库
在spring配置文件中配置了事务管理 <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 开启事务注解 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 开启注解扫描 --> <context:component-scan base-package="com"></context:component-scan > 而且在类上面也开启了事务注解: import javax.transaction.Transactional; import com.dao.YongHuDao; import com.entity.YongHu; import com.service.YongHuService; @Transactional public class YongHuServiceImpl implements YongHuService { private YongHuDao yhdi; @Override public void add(YongHu t) { yhdi.add(t); } 控制台没有错误信息,只输出一条查询伪表id的sql语句: DEBUG - Found thread-bound Session for HibernateTemplate DEBUG - trace com.mchange.v2.resourcepool.BasicResourcePool@58aff4cd [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@49056629) Hibernate: select hibernate_sequence.nextval from dual DEBUG - Not closing pre-bound Hibernate Session after HibernateTemplate hahahhaah26hahahahhahha DEBUG - Entering nullPropertyValue [target=[com.entity.YongHu@2e81070, com.action.UserAction@3e625613, com.opensymphony.xwork2.DefaultTextProvider@17e36931], property=struts] DEBUG - Entering nullPropertyValue [target=[com.entity.YongHu@2e81070, com.action.UserAction@3e625613, com.opensymphony.xwork2.DefaultTextProvider@17e36931], property=org] DEBUG - after Locale=zh_CN 实在找不出哪里错了,求大神解答
SSH框架中的有关数据库的问题
我其他没有问题,就是连接数据库可能有问题,但是程序也能初始化成功,但在执行具体sql的时候,不能执行 [b]java.lang.NullPointerException at com.test.dao.BaseDaoImpl.loadObject(BaseDaoImpl.java:29) at com.test.service.impl.UserServiceImpl.selectUserByNumber(UserServiceImpl.java:38) at com.test.struts.action.UserAction.selectUserByNumber(UserAction.java:90) 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:441) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.test.struts.interceptor.LoggerInterceptor.intercept(LoggerInterceptor.java:42) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at com.opensymphony.xwork2.interceptor.TimerInterceptor.invokeUnderTiming(TimerInterceptor.java:124) at com.opensymphony.xwork2.interceptor.TimerInterceptor.intercept(TimerInterceptor.java:111) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) 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:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source)[/b] 这是我的其中spring和hibernate的配置文件 [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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 开启注解处理器 --> <context:annotation-config/> <!-- 定义使用C3P0连接池的数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 指定连接数据库的JDBC驱动 --> <property name="driverClass"> <value>com.mysql.jdbc.Driver</value> </property> <!-- 连接数据库所用的URL --> <property name="jdbcUrl"> <value>jdbc:mysql://localhost:3306/softtest?useUnicode=true&amp;characterEncoding=utf-8</value> </property> <!-- 连接数据库的用户名 --> <property name="user"> <value>root</value> </property> <!-- 连接数据库的密码 --> <property name="password"> <value>root</value> </property> <!-- 设置数据库连接池的最大连接数 --> <property name="maxPoolSize"> <value>20</value> </property> <!-- 设置数据库连接池的最小连接数 --> <property name="minPoolSize"> <value>2</value> </property> <!-- 设置数据库连接池的初始化连接数 --> <property name="initialPoolSize"> <value>2</value> </property> <!-- 设置数据库连接池的连接的最大空闲时间,单位为秒 --> <property name="maxIdleTime"> <value>20</value> </property> </bean> <!-- 定义Hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 依赖注入上面定义的数据源dataSource --> <property name="dataSource" ref="dataSource"/> <!-- 注册Hibernate的ORM映射文件 --> <property name="mappingResources"> <list> <value>com/test/orm/FaultInfo.hbm.xml</value> <value>com/test/orm/ModelInfo.hbm.xml</value> <value>com/test/orm/ProjectInfo.hbm.xml</value> <value>com/test/orm/UserInfo.hbm.xml</value> <value>com/test/orm/UserModel.hbm.xml</value> <value>com/test/orm/UserFault.hbm.xml</value> <value>com/test/orm/UserProject.hbm.xml</value> <value>com/test/orm/FaultType.hbm.xml</value> <value>com/test/orm/Logger.hbm.xml</value> </list> </property> <!-- 设置Hibernate的相关属性 --> <property name="hibernateProperties"> <props> <!-- 设置Hibernate的数据库方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!-- 设置Hibernate是否在控制台输出SQL语句,开发调试阶段通常设为true --> <prop key="show_sql">true</prop> <!-- 设置Hibernate一个提交批次中的最大SQL语句数 --> <prop key="hibernate.jdbc.batch_size">50</prop> </props> </property> </bean> <!--定义Hibernate的事务管理器HibernateTransactionManager --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <!-- 依赖注入上面定义的sessionFactory --> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 装配HibernateTemplate实例 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <constructor-arg ref="sessionFactory"/> </bean> </beans> [/code] 这是我的数据库操作代码 [code="java"] public Object loadObject(String hql) { final String hql1 = hql; Object obj = null; try { List list = hibernateTemplate.executeFind(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query query = session.createQuery(hql1); return query.list(); } }); if (list.size() > 0) { obj = list.get(0); } } catch (Exception e) { e.printStackTrace(); } return obj; } [/code]
一些关于SSH配置的问题
刚开始自学SSH,从网上找的demo里的配置文件里事务管理有几段不了解的地方, 在网上找不到,求热心人解释一下,最好稍微解释细点,标头和属性还有每一段的作用。。谢谢! <!-- 使用HibernateTransactionManager管理hibernate事务。 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!--事务控制数据库 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置那些类的方法进行事务管理 --> <aop:config> <aop:pointcut id="bussinessService" expression="execution(public * com.huake.service.*.*(..))" /> <aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="exists" read-only="true" /> <tx:method name="add*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> </beans>
SSH2 访问多个数据库出现的问题!经常远程连接不上!
SSH2 框架 系统运行了几个月 现在数据才1W多条 但是关联太多 导致系统显示分页100条记录就很慢 现在接手这个项目很多地方都要重新修改。。 现在框架重新搭的时候碰到一个问题 最痛苦 美国有一台服务器主要是读取其他服务器数据库的所有订单 客户信息,国内服务器连接国外把数据库读取回来。 我用spring 配置了2个数据源 配置信息如下: [code="java"] <bean id="aDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/yilainetwork?characterEncoding=utf-8"></property> <property name="user" value="*********"></property> <property name="password" value="*********"></property> <property name="minPoolSize" value="5" ></property> <property name="maxPoolSize" value="50"></property> <property name="maxIdleTime" value="60"></property> <property name="acquireIncrement" value="3"></property> <property name="maxStatements" value="0"></property> <property name="idleConnectionTestPeriod" value="60"></property> <property name="acquireRetryAttempts" value="10"></property> <property name="breakAfterAcquireFailure" value="false"></property> <property name="acquireRetryDelay" value="10000"></property> <property name="testConnectionOnCheckin" value="true"></property> <property name="testConnectionOnCheckout" value="true"></property> </bean> <bean id="bDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://*********:3306/yilainetwork?characterEncoding=utf-8"></property> <property name="user" value="*********"></property> <property name="password" value="*********"></property> <property name="minPoolSize" value="5" ></property> <property name="maxPoolSize" value="50"></property> <property name="maxIdleTime" value="60"></property> <property name="acquireIncrement" value="3"></property> <property name="maxStatements" value="0"></property> <property name="idleConnectionTestPeriod" value="60"></property> <property name="acquireRetryAttempts" value="10"></property> <property name="breakAfterAcquireFailure" value="false"></property> <property name="acquireRetryDelay" value="10000"></property> <property name="testConnectionOnCheckin" value="true"></property> <property name="testConnectionOnCheckout" value="true"></property> </bean> [/code] 经常性报错 错误信息 [code="java"] Exception in thread "timerFactory" org.springframework.dao.DataAccessResourceFailureException: could not execute query; nested exception is org.hibernate.exception.JDBCConnectionException: could not execute query at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:625) at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912) at com.yilainetwork.dao.CommonDao.findByHqlC(CommonDao.java:96) 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:307) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:108) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy16.findByHqlC(Unknown Source) at com.yilainetwork.service.impl.OrdersService.findOrdersC(OrdersService.java:229) at com.yilainetwork.util.testConnectionData.run(testConnectionData.java:31) at java.util.TimerThread.mainLoop(Timer.java:512) at java.util.TimerThread.run(Timer.java:462) Caused by: org.hibernate.exception.JDBCConnectionException: could not execute query at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.loader.Loader.doList(Loader.java:2235) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:921) at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) ... 20 more Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 84640 ms ago. 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 com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3009) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2895) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3438) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1912) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1812) at org.hibernate.loader.Loader.doQuery(Loader.java:697) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) ... 30 more Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:168) at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113) at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160) at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2452) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2906) ... 43 more [/code] 或者前面一样最后的错误信息不是Connection reset [code="java"] Caused by: java.io.EOFException: Can not read response from server. Expected to read 255 bytes, read 0 bytes before connection was unexpectedly lost. at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2455) at com.mysql.jdbc.MysqlIO.nextRowFast(MysqlIO.java:1626) ... 47 more [/code] 或者报下面这个错误!! [code="java"] Exception in thread "timerFactory" org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: JDBC commit failed at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:660) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:412) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at $Proxy16.findByHqlC(Unknown Source) at com.yilainetwork.service.impl.OrdersService.findOrdersC(OrdersService.java:229) at com.yilainetwork.util.testConnectionData.run(testConnectionData.java:33) at java.util.TimerThread.mainLoop(Timer.java:512) at java.util.TimerThread.run(Timer.java:462) Caused by: org.hibernate.TransactionException: JDBC commit failed at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:161) at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:656) ... 13 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Communications link failure during commit(). Transaction resolution unknown. 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 com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) at com.mysql.jdbc.ConnectionImpl.commit(ConnectionImpl.java:1569) at com.mchange.v2.c3p0.impl.NewProxyConnection.commit(NewProxyConnection.java:803) at org.hibernate.transaction.JDBCTransaction.commitAndResetAutoCommit(JDBCTransaction.java:170) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:146) ... 14 more [/code] 原本读取美国服务器的订单是通过直接JAVA JDBC Connection 来连接 也是会经常报 Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Last packet sent to the server was 84640 ms ago. 这个错误 数据库都能连接上去 但是就是直接SQL的时候 ResultSet rs = pstmt.executeQuery(); 获取ResultSet值的时候报错! 在网上找了一些资料 修改MYSQL wait_timeout 8小时等待 时间 也是不行! 一直测试MYSQL的连接 SPRING 配置的C3P0 连接池参数 还是不行!! 如果用C3P0做连接池的话 执行HQL 错误的几率大!! 如果是执行SQL的话 因为读取订单信息关联3 4张表的信息!!数据得重新封装!!但是还是会报错! 有的时候会报事务没有提交!! Spring 事务配置信息 [code="java"] <!-- 事务管理 --> <!-- Transaction beans start --> <!-- 数据源1事务托管 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="aSessionFactory" /> </property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="sav*" propagation="REQUIRED"/> <tx:method name="dele*" propagation="REQUIRED"/> <tx:method name="inse*" propagation="REQUIRED"/> <tx:method name="upda*" propagation="REQUIRED"/> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="allManagerMethod" expression="execution(* com.**.dao.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/> </aop:config> <!-- Transaction beans end --> [/code] 因为Spring 配置了俩个 数据源 我有一个切换数据库的方法 网上找的 事务我就直接还是根据其他人的 这样写! 这个问题 到底应该如何解决!! 我对MYSQL my.ini 的[mysqld]增加了 skip-name-resolve
SSH框架的InvalidDataAccessApiUsageException问题
在SSH项目中,执行save方法时报错,求解答。 ``` org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition. ``` spring配置文件 ``` <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置spring创建容器时要扫描的包 --> <context:component-scan base-package="com.wzjpro"></context:component-scan> <!-- 配置hibernateTemplate --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <!-- 连接数据库,用连接池 --> <property name="dataSource" ref="dataSource"></property> <!-- hibernate的可选配置 --> <property name="hibernateProperties"> <props> <!-- 数据库的方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!--是否显示hibernate生成的SQL语句 --> <prop key="hibernate.show_sql">true</prop> <!-- 是否使用格式化输出sql语句的控制台 --> <prop key="hibernate.format_sql">false</prop> <!-- 配置hibernate采用何种方式生成DDL语句 --> <prop key="hibernate.hbm2ddl.auto">update</prop> <!-- 把session和线程绑定,从而实现一个线程只有一个Session --> <prop key="hibernate.current_session_context_class">org.springframework.hibernate5.SpringSessionContext</prop> </props> </property> <!-- 指定映射文件的位置 --> <property name="packagesToScan"> <array> <value>com.wzjpro.domain</value> </array> </property> </bean> <!-- 配置dataSource --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/crm_ssh"></property> <property name="user" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 开启spring对注解事务的支持 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 在业务层需要使用事务的地方使用@Transactional注解 --> </beans> ``` 业务层代码 ``` package com.wzjpro.service.impl; import java.util.List; import javax.annotation.Resource; import org.hibernate.criterion.DetachedCriteria; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.wzjpro.dao.ICustomerDao; import com.wzjpro.domain.Customer; import com.wzjpro.service.ICustomerService; /** * 客户的业务层实现类 * @author Administrator * */ @Service("customerService") @Transactional(readOnly=true,propagation=Propagation.SUPPORTS) public class CustomerServiceImpl implements ICustomerService { @Resource(name="customerDao") private ICustomerDao customerDao; @Override public List<Customer> findAllCustomer(DetachedCriteria dCriteria) { return customerDao.findAllCustomer(dCriteria); } @Override @Transactional(readOnly=false,propagation=Propagation.REQUIRED) public void saveCustomer(Customer customer) { customerDao.save(customer); } } ```
使用子查询和伪列,在oracle数据库中能查到信息,放在后台却报错
select ROWNUM,vv from (select sum(totalCount),year from com.jbit.entity.VouyearStatistics GROUP BY year) as vv; 就是这句hql语句,放在数据库那边可以查得到数据,放在ssh后台就报错。 org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: ( near line 1, column 23 [select ROWNUM,vv from (select sum(totalCount),year from com.jbit.entity.VouyearStatistics GROUP BY year) as vv]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 23 [select ROWNUM,vv from (select sum(totalCount),year from com.jbit.entity.VouyearStatistics GROUP BY year) as vv] org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:656) org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411) org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912) org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:904) com.jbit.dao.impl.VouyearStatisticsDaoImpl.getAllByManageByEmp(VouyearStatisticsDaoImpl.java:42) com.jbit.service.impl.VouyearStatisticsServiceImpl.getAllByManageByEmp(VouyearStatisticsServiceImpl.java:34) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:606) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) com.sun.proxy.$Proxy16.getAllByManageByEmp(Unknown Source) com.jbit.action.VouyearStatisticsAction.showVouyearByDept(VouyearStatisticsAction.java:48) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:606) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
为什么我用hibernaetemplate.delete方法无法删除数据库中的数据
在我的ssh架构下有一张部门信息表department,现在我想删除里面的数据,dao的实现方式如下: public void delete(Department department) { //System.out.println(department.getId()); this.hibernateTemplate.delete(department); } 添加数据是没有问题的,部署调试时,打印主键值也没有问题,通过在jsp页面地址中手动传值,日志显示如下: Hibernate: select department_.id, department_.name as name0_, department_.sort as sort0_ from Department department_ where department_.id=? 我刚接触java,搞不懂为什么调用delete方法却出现的是select结果,我的SSH版本分别是Spring 3.1+Hibernate 3.6.10+struts 2.3.1.2。弄了一个下午也搞不懂,请大家帮忙指点是什么问题啊!
Spring Hibernate 整合问题?急
我写了一个小的ssh的demo,在tomcat下配置好后,启动没有报任何错误,service中用到hibernatetemplate,是用spring注入进去的,使用save方法想保存对象,控制台已经显示输出了insert语句,但数据库为插入任何记录.用debug查看hibernatetemplate,sessionFactory都有取到对象,但就是插入不了记录.帮忙分析下,是什么原因呢? 有没有遇到这种情况解决过的?
java.lang.IllegalStateException: Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:91) at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:74) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:116) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/EntityListeners at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1568) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:540) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:260) at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:63) at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:83) ... 25 more Caused by: java.lang.NoClassDefFoundError: javax/persistence/EntityListeners at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(JPAMetadataProvider.java:96) at org.hibernate.annotations.common.reflection.java.JavaReflectionManager.getDefaults(JavaReflectionManager.java:226) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1385) at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:658) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:189) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1627) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1564) ... 40 more Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityListeners at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 48 more 在SSH整合的时候遇见的错误,我的applicationContext.xml代码如下: <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载hibernate.cfg.xml 获得SessionFactory --> <bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 确定配置文件的位置 --> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> </bean> <!-- 创建模板 --> <bean name="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- dao --> <bean name="userDao" class="com.shanmu.dao.impl.UserDaoImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> <!-- service --> <bean name="userService" class="com.shanmu.service.impl.UserServiceImpl"> <property name="userDao" ref="userDao"></property> </bean> <!-- 事务管理 --> <!-- 事务管理器:HibernateTransactionManager --> <bean name="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 事务详情 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="register"/> </tx:attributes> </tx:advice> <!-- AOP编程 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.shanmu.service..*.*(..))"/> </aop:config> </beans> 但是一直报错,检查过代码问题没有错,检查过数据库,检查过路径,都没有错,网上的方法基本都试了,也没有错 求解
org.hibernate.exception.SQLGrammarException: could not insert:
用的框架 Struts2+Hibernate3+Spring3 数据库为:SQLServer2005 环境是:Myeclipse8.5 服务器为:apache-tomcat-8.0.0-RC1 问题:在我尝试通过struts2 action向数据库插入数据是出现异常。 异常信息如下: Struts Problem Report Struts has detected an unhandled exception: Messages: '107' ???????? could not insert: [com.gxwz.entity.GxUser] could not insert: [com.gxwz.entity.GxUser]; SQL [insert into 107gxwz.dbo.gx_user (UName, UPwd, UGender, UEmal, URole, UHead, URegDate, ULastLogin, ULastEmit, UPermit, UMobile, UUploadFilesIDs, UDownLoadFileIDs, UUrl, UTopicIDs, URevertIDs) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [com.gxwz.entity.GxUser] File: com/microsoft/sqlserver/jdbc/SQLServerException.java Line number: 216 -------------------------------------------------------------------------------- Stacktraces org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert: [com.gxwz.entity.GxUser]; SQL [insert into 107gxwz.dbo.gx_user (UName, UPwd, UGender, UEmal, URole, UHead, URegDate, ULastLogin, ULastEmit, UPermit, UMobile, UUploadFilesIDs, UDownLoadFileIDs, UUrl, UTopicIDs, URevertIDs) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [com.gxwz.entity.GxUser] org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:629) org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411) org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683) com.gxwz.dao.impl.UserDaoImpl.add(UserDaoImpl.java:30) com.gxwz.service.impl.UserServiceImpl.add(UserServiceImpl.java:35) com.gxwz.action.UserAction.addUser(UserAction.java:47) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:606) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:223) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:107) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:75) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:90) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:494) org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009) org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:632) org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:281) org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2248) org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2237) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) java.lang.Thread.run(Thread.java:724) org.hibernate.exception.SQLGrammarException: could not insert: [com.gxwz.entity.GxUser] org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90) org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64) org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2176) org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2656) org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71) org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321) org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204) org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130) org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210) org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56) org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195) org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50) org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93) org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:563) org.hibernate.impl.SessionImpl.save(SessionImpl.java:551) org.hibernate.impl.SessionImpl.save(SessionImpl.java:547) org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:686) org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:1) org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:683) com.gxwz.dao.impl.UserDaoImpl.add(UserDaoImpl.java:30) com.gxwz.service.impl.UserServiceImpl.add(UserServiceImpl.java:35) com.gxwz.action.UserAction.addUser(UserAction.java:47) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:606) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) 。。。。。。。。。。。。省略。。。。。。 配置文件如下: <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd"> <!-- hibernate配置开始 --> <beans> <!-- 数据源注入session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="mappingResources"> <list> <value>com/gxwz/entity/GxUser.hbm.xml</value> </list> </property> </bean> <!-- 配置数据库连接池开始--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"> </property> <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=107gxwz"> </property> <property name="username" value="sa"></property> <property name="password" value="root"></property> </bean> <!-- 配置数据库连接池结束--> <!-- 声明事物管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="jdbcExceptionTranslator" class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref local="sessionFactory" /> </property> <property name="jdbcExceptionTranslator" ref="jdbcExceptionTranslator" /> </bean> </beans> 我的实体映射文件如下: <hibernate-mapping> <class name="com.gxwz.entity.GxUser" table="gx_user" schema="dbo" catalog="107gxwz"> <id name="uid" type="java.lang.Integer"> <column name="UId" /> <generator class="native"></generator> </id> <property name="uname" type="java.lang.String"> <column name="UName" length="20" not-null="true" /> </property> <property name="upwd" type="java.lang.String"> <column name="UPwd" length="20" not-null="true" /> </property> <property name="ugender" type="java.lang.String"> <column name="UGender" length="4" not-null="true" /> </property> <property name="uemal" type="java.lang.String"> <column name="UEmal" length="50" not-null="true" /> </property> <property name="urole" type="java.lang.Integer"> <column name="URole" not-null="true" /> </property> <property name="uhead" type="java.lang.String"> <column name="UHead" length="50" /> </property> <property name="uregDate" type="java.sql.Timestamp"> <column name="URegDate" length="23" /> </property> </class> </hibernate-mapping> 跪求大虾指点一二。。。。在网上找了好久都没解决。。。。
SSH中Struts2获取不到jsp页面中值,求大神指点
ssh框架整合,添加员工信息; 员工,Emp: ``` package com.blue.entity; public class Emp { //id,数据库中为标识列 private int empId; //姓名 private String empName; //年龄 private int empAge; //性别 private String empSex; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getEmpAge() { return empAge; } public void setEmpAge(int empAge) { this.empAge = empAge; } public String getEmpSex() { return empSex; } public void setEmpSex(String empSex) { this.empSex = empSex; } } ``` jsp页面,form: ``` <form action="empLogin" method="post"> <table width="300px" height="150px" border="1px"> <tr> <td width="100px">姓名:</td> <td><input type="text" name="emp.empName"/></td> </tr> <tr> <td>年龄:</td> <td><input type="text" name="emp.empAge"/></td> </tr> <tr> <td>性别:</td> <td><input type="text" name="emp.empSex"/></td> </tr> <tr> <td colspan="2"><input type="submit" value="保存"></td> </tr> </table> </form> ``` action: ``` package com.blue.action; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.blue.entity.Emp; import com.blue.service.EmpService; import com.opensymphony.xwork2.ActionSupport; public class EmpAction extends ActionSupport{ public String result(){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); EmpService empService= (EmpService) context.getBean("empService"); Emp emp = (Emp) context.getBean("emp"); //测试 System.out.println("id:"+emp.getEmpId()+" name:"+emp.getEmpName()+" age:"+emp.getEmpAge()+" sex:"+emp.getEmpSex()); int num = empService.save(emp); if(num == -1){ //值为空 return "empty"; }else if(num > 0){ //添加成功 return SUCCESS; }else{ //失败 return ERROR; } } } 控制台输出: id:0 name:null age:0 sex:null ``` spring配置文件(beans.xml): ``` <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value> classpath:hibernate.cfg.xml </value> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="emp" class="com.blue.entity.Emp"></bean> <bean id="empDao" class="com.blue.dao.impl.EmpDaoImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> <bean id="empService" class="com.blue.service.impl.EmpServiceImpl"> <property name="empDao" ref="empDao"></property> </bean> <bean id="empAction" class="com.blue.action.EmpAction" scope="prototype"></bean> </beans> ``` struts.xml: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.objectFactory" value="spring"></constant> <package name="default" namespace="/" extends="struts-default"> <action name="empLogin" class="com.blue.action.EmpAction" method="result"> <result name="success">welcome.jsp</result> <result name="error">error.jsp</result> <!-- 空值 --> <result name="empty">empty.jsp</result> </action> </package> </struts> ``` 包结构: ![图片说明](https://img-ask.csdn.net/upload/201610/02/1475398814_503001.png) 取不到页面值,求大神指点
c3p0 连接不释放 请路过的大神过来看看
配置文件如下 <?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <!-- 打开Spring的Annotation支持 --> <!-- 设定Spring 去哪些包中找Annotation --> <context:component-scan base-package="com.myd" /> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${driverClass}" /> <property name="jdbcUrl" value="${jdbcUrl}" /> <property name="user" value="${username}" /> <property name="password" value="${password}" /> <!-- 配置连接池的初始值 --> <property name="acquireIncrement" value="${acquireIncrement}" /> <property name="maxPoolSize" value="${maxPoolSize}" /> <property name="minPoolSize" value="${minPoolSize}" /> <property name="initialPoolSize" value="${initialPoolSize}" /> <property name="maxIdleTime" value="${maxIdleTime}" /> <property name="checkoutTimeout" value="${checkoutTimeout}" /> <property name="autoCommitOnClose" value="${autoCommitOnClose}"></property> <property name="acquireRetryDelay" value="${acquireRetryDelay}" /> <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"></property> <property name="maxStatements" value="${maxStatements}"></property> <property name="numHelperThreads" value="${numHelperThreads}"></property> </bean> <!-- 导入src目录下的c3p0.properties文件 --> <context:property-placeholder location="classpath:c3p0.properties" /> <!--创建Spring的SessionFactory工厂 --> <!-- 如果使用的是Annotation的方式,不能使用LocalSessionFactoryBean,而应该使用 org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 设置Spring取那个包中查找相应的实体类 --> <property name="packagesToScan"> <value>com.myd.entity</value> </property> <property name="hibernateProperties"> <!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.autoReconnect">true</prop> <prop key="jdbc.use_scrollable_resultset">false</prop> <prop key="hibernate.connection.release_mode">after_statement</prop> <prop key="hibernate.c3p0.validate">true</prop> <prop key="hibernate.c3p0.idle_test_period">30</prop> <prop key="hibernate.c3p0.timeout">30</prop> <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</prop> </props> </property> </bean> <!-- 开启HibernateTemplate,并且为其注入SessionFactory 使用HibernateTemplate不太方便的就是要获取session得通过getSessionFactory()方法获取 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置Spring的事务处理 --> <!-- 创建事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置AOP,Spring是通过AOP来进行事务管理的 --> <aop:config> <!-- 设置pointCut表示哪些方法要加入事务处理 --> <!-- 以下的事务是声明在DAO中,但是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常 就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service,这也就是Spring所提供的一个非常方便的工具,声明式事务 --> <aop:pointcut id="allMethods" expression="execution(* com.myd.service.*.*(..))" /> <!-- 通过advisor来确定具体要加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> </aop:config> <!-- 配置哪些方法要加入事务控制 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> <tx:method name="*" propagation="REQUIRED" read-only="true" /> <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 --> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="5" /> <property name="maxPoolSize" value="50" /> <property name="queueCapacity" value="1000" /> <property name="keepAliveSeconds" value="60" /> </bean> </beans> 这是事务 package com.myd.dao.impl; import java.lang.reflect.ParameterizedType; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.transform.Transformers; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Repository; import com.myd.dao.BaseDao; /** * 可以考虑把所有公共的方法都写在baseDAo中,让所有的DAO都继承BaseDao * 这样基本上就实现了大量的基础方法,如果DAO中有逻辑处理特殊的方法,再在具体的实现类中的DAO中创建 * * @author Administrator * * @param <T> */ @Repository("baseDaoImpl") public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> { /** * 此处不能使用setSessionFactory注入,因为setSessionFactory在HibernateDaoSupport * 中已经定义了而且还是final的,不能被覆盖 * * @param sessionFactory */ @Resource(name = "sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } /** * 创建Class的对象来获取泛型的class */ private Class<Object> clz; @SuppressWarnings("unchecked") public Class<Object> getClz() { if (clz == null) { // 获取泛型的Class对象 clz = (Class<Object>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } return clz; } public void add(T t) { getHibernateTemplate().getSessionFactory().openSession(); getHibernateTemplate().save(t); getHibernateTemplate().getSessionFactory().close(); } public void delete(int id) { getHibernateTemplate().getSessionFactory().openSession(); getHibernateTemplate().delete(load(id)); getHibernateTemplate().getSessionFactory().close(); } @SuppressWarnings("deprecation") public void update(T t) { try { getHibernateTemplate().getSessionFactory().openSession() .connection().prepareStatement("SET SQL_SAFE_UPDATES=0") .execute(); } catch (DataAccessResourceFailureException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } getHibernateTemplate().update(t); getHibernateTemplate().getSessionFactory().close(); } 现在的问题是 运行一段时间后,就卡起, 不是报连接数据库关闭 就是 返回空指针 查了以下是连接未释放导致的,我想请教下各位大神 我这样连接没关闭并回到连接池吗?
tomcat 404问题,console出的问题有关于mysql数据库连接问题,账号密码错误等问题。萌新求帮助!!
复制的一个网站项目,想要再localhost尝试看看,但网页404,查询问题发现mysql链接有问题。 试图尝试解决,但无功而返。刚开始自学水平很差,能有大神帮忙耐心指点吗?谢谢 如果能帮我解决问题有重谢。可以加q或v帮助下小弟! 以下是console结果(如果需要什么代码,可随时复制黏贴): 、 INFO: Initializing Spring root WebApplicationContext 11:28:29,539 INFO ContextLoader:305 - Root WebApplicationContext: initialization started 11:28:29,613 INFO XmlWebApplicationContext:578 - Refreshing Root WebApplicationContext: startup date [Tue Dec 04 11:28:29 CST 2018]; root of context hierarchy 11:28:29,652 INFO XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [applicationContext.xml] 11:28:29,811 INFO XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [applicationContext-dataSource.xml] 11:28:29,952 INFO PropertySourcesPlaceholderConfigurer:172 - Loading properties file from class path resource [jdbc.properties] 11:28:30,020 INFO MLog:80 - MLog clients using log4j logging. 11:28:30,047 INFO C3P0Registry:204 - Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10] 11:28:30,214 INFO Version:37 - HHH000412: Hibernate Core {5.0.1.Final} 11:28:30,216 INFO Environment:213 - HHH000206: hibernate.properties not found 11:28:30,217 INFO Environment:317 - HHH000021: Bytecode provider name : javassist 11:28:30,261 INFO Version:66 - HCANN000001: Hibernate Commons Annotations {5.0.0.Final} 11:28:30,381 INFO AbstractPoolBackedDataSource:462 - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge75i9zx396c51lmbo3k|1bf951e0, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge75i9zx396c51lmbo3k|1bf951e0, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql://localhost:3306/test?characterEncoding=utf-8, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ] 11:28:59,645 WARN BasicResourcePool:1841 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@1d4e6cb -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:870) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1659) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1206) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) at sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 11:28:59,650 WARN JdbcEnvironmentInitiator:132 - HHH000342: Could not obtain connection to query metadata : Connections could not be acquired from the underlying database! 11:28:59,652 WARN BasicResourcePool:1841 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@5453f660 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:870) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1659) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1206) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) at sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 11:28:59,652 WARN BasicResourcePool:1841 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@68345260 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:870) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1659) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1206) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) at sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 11:28:59,720 INFO Dialect:154 - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect 11:28:59,744 INFO LobCreatorBuilderImpl:63 - HHH000422: Disabling contextual LOB creation as connection was null 11:29:00,395 INFO SchemaUpdate:101 - HHH000228: Running hbm2ddl schema update 11:29:29,549 WARN BasicResourcePool:1841 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@6aad2b9c -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:870) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1659) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1206) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) at sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 11:29:29,554 WARN XmlWebApplicationContext:546 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderInfoDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.itheima.dao.impl.OrderInfoDaoImpl.setHT(org.springframework.orm.hibernate5.HibernateTemplate); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-dataSource.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target 11:29:29,567 ERROR ContextLoader:351 - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderInfoDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.itheima.dao.impl.OrderInfoDaoImpl.setHT(org.springframework.orm.hibernate5.HibernateTemplate); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-dataSource.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1218) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:778) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1245) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1895) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.itheima.dao.impl.OrderInfoDaoImpl.setHT(org.springframework.orm.hibernate5.HibernateTemplate); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-dataSource.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:661) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 27 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-dataSource.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1230) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1123) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1021) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:618) ... 29 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1582) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ... 42 more Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.hibernate.tool.schema.internal.TargetDatabaseImpl.prepare(TargetDatabaseImpl.java:42) at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:56) at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:129) at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:97) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:481) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724) at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:416) at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:401) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1641) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ... 49 more Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database! at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) at org.hibernate.tool.schema.internal.TargetDatabaseImpl.prepare(TargetDatabaseImpl.java:38) ... 60 more Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525) ... 64 more 十二月 04, 2018 11:29:29 上午 org.apache.catalina.core.StandardContext listenerStart SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orderInfoDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.itheima.dao.impl.OrderInfoDaoImpl.setHT(org.springframework.orm.hibernate5.HibernateTemplate); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-dataSource.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1218) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:778) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4994) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:649) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1245) at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1895) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.itheima.dao.impl.OrderInfoDaoImpl.setHT(org.springframework.orm.hibernate5.HibernateTemplate); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-dataSource.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:661) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 27 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext-dataSource.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1230) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1123) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1021) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:618) ... 29 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dataSource.xml]: Invocation of init method failed; nested exception is org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1582) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) ... 42 more Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to open JDBC connection for schema management target at org.hibernate.tool.schema.internal.TargetDatabaseImpl.prepare(TargetDatabaseImpl.java:42) at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:56) at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:129) at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:97) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:481) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724) at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:416) at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:401) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1641) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ... 49 more Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database! at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) at org.hibernate.tool.schema.internal.TargetDatabaseImpl.prepare(TargetDatabaseImpl.java:38) ... 60 more Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525) ... 64 more 十二月 04, 2018 11:29:29 上午 org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart 11:29:29,570 WARN BasicResourcePool:1841 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@3e5739e3 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:870) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1659) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1206) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) at sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 11:29:29,570 WARN BasicResourcePool:1841 - com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@f302a79 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:996) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:870) at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1659) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1206) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2234) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2265) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2064) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44) at sun.reflect.GeneratedConstructorAccessor21.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:525) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:395) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:325) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 十二月 04, 2018 11:29:29 上午 org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/ssh] startup failed due to previous errors 十二月 04, 2018 11:29:29 上午 org.apache.catalina.core.ApplicationContext log INFO: Closing Spring root WebApplicationContext 十二月 04, 2018 11:29:29 上午 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc SEVERE: The web application [/ssh] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. 十二月 04, 2018 11:29:29 上午 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: The web application [/ssh] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak. 十二月 04, 2018 11:29:29 上午 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: The web application [/ssh] appears to have started a thread named [com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#0] but has failed to stop it. This is very likely to create a memory leak. 十二月 04, 2018 11:29:29 上午 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: The web application [/ssh] appears to have started a thread named [com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#1] but has failed to stop it. This is very likely to create a memory leak. 十二月 04, 2018 11:29:29 上午 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: The web application [/ssh] appears to have started a thread named [com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread-#2] but has failed to stop it. This is very likely to create a memory leak. 十二月 04, 2018 11:29:29 上午 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: The web application [/ssh] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. 十二月 04, 2018 11:29:29 上午 org.apache.catalina.startup.HostConfig deployDirectory INFO: Deployment of web application directory E:\apache-tomcat-7.0.57\webapps\ssh has finished in 61,100 ms 十二月 04, 2018 11:29:29 上午 org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-apr-8080"] 十二月 04, 2018 11:29:29 上午 org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-apr-8009"] 十二月 04, 2018 11:29:29 上午 org.apache.catalina.startup.Catalina start INFO: Server startup in 61993 ms
Hibernate 的 getSessionFactory();方法
在下自学Hibernate方法,有错误之处请各位多多指点 废话少说直接上代码 DAOImpl 中的代码: public class UserDAOImpl extends HibernateTemplate implements UserDAO { private SessionFactory factory; @Override public User findUserByName(String name) { System.out.println("进来了DAO层"); try{ //修改开始处 Configuration conf = new Configuration(); conf = conf.configure(); factory = conf.buildSessionFactory(); //修改结束处 }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } Session session = factory.openSession(); Transaction tx = null; List<User> users = new ArrayList<User>(); try{ tx = session.beginTransaction(); String hql = "FROM User U WHERE U.name = :name"; Query query = session.createQuery(hql); query.setParameter("name",name); users = (List<User>)query.list(); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return users.get(0); } public void setFactory(SessionFactory factory) { this.factory = factory; } } dao.xml 中的配置: <bean id="userDAO" class="com.ssh.dao.UserDAOImpl"> <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> # 这种情况下,系统是没有错的.只不过查询的结果非常慢 所以我准备换成用Spring来管理hibernate的数据库懒加载 为了大家看的明白 我就只修改了 //修改开始处 和//修改结束处 中间的代码 替换成了: factory = this.getHibernateTemplate().getSessionFactory(); 就这样,系统就报错了 贴上错误提示 ``` org.hibernate.hql.ast.QuerySyntaxException: User is not mapped. [FROM User U WHERE U.name = :name] at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:157) at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87) at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70) at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:265) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3049) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2938) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:218) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:158) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:109) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:75) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:54) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:71) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1583) at com.ssh.dao.UserDAOImpl.findUserByName(UserDAOImpl.java:44) at com.ssh.service.UserServiceImpl.getUserByUserName(UserServiceImpl.java:14) at com.ssh.action.loginAction.login(loginAction.java:14) 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:497) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263) 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:248) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) 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:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:745) Caused by: User is not mapped. ... 87 more ``` 提示 User is not mapped (我是知道hql中的User 并不是数据库中的表名,所以这里不会错的) 那么为什么会提示User没有在数据库中映射???? 所以请问各位大神这是错在哪了.有需要贴别的地方的代码请尽管说. 我把我所有的币都献上了 应要求 贴上user.hbm.xml的代码: ``` <hibernate-mapping> <class name="com.ssh.entity.User" table="user"> <id name="id" type="int" column="id"> </id> <property name="name" column="name" type="string"/> <property name="password" column="password" type="string"/> </class> </hibernate-mapping> ```
ssh的spring 无法注入怎么回事
<strong>UserInfoDAOImpl.java</strong> <br /><pre name="code" class="java">@Service public class UserInfoDAOImpl extends HibernateDaoSupport implements UserInfoDAO { public boolean login(Userinfo userinfo) { boolean isExist = false; Userinfo temp = (Userinfo)this.getHibernateTemplate().find("from Userinfo u where u.username=?", userinfo.getUsername()).get(0); try { if(userinfo.getPassword().equals(temp.getPassword())) isExist = true; } catch(Exception e) { e.printStackTrace(); } System.out.println("id:" + temp.getId()); System.out.println("username:" + temp.getUsername()); System.out.println("password:" + temp.getPassword()); System.out.println("isExist:" + isExist); return isExist; } }</pre> <br /><strong>LoginAction.java</strong> <br /><pre name="code" class="java">@Component @Results(value={ @Result(name="success", location="/login_success.jsp"), @Result(name="fail", location="/Login.jsp") }) public class LoginAction extends ActionSupport { private Userinfo userinfo; @Autowired private UserInfoDAO userInfoDAOImpl; public Userinfo getUserinfo() { return userinfo; } public void setUserinfo(Userinfo userinfo) { this.userinfo = userinfo; } public UserInfoDAO getUserInfoDAOImpl() { return userInfoDAOImpl; } public void setUserInfoDAOImpl(UserInfoDAO userInfoDAOImpl) { System.out.println("注入"); this.userInfoDAOImpl = userInfoDAOImpl; } @Action("login") public String login() { System.out.println("id:" + userinfo.getId()); System.out.println("username:" + userinfo.getUsername()); System.out.println("password:" + userinfo.getPassword()); if(userInfoDAOImpl == null) System.out.println("error"); if(userinfo == null) return "fail"; else return (userInfoDAOImpl.login(userinfo))?"success":"fail"; } }</pre> <br /><strong>applicationContext.xml</strong> <br /><pre name="code" class="java">&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:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-lazy-init="true"&gt; &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /&gt; &lt;property name="ignoreResourceNotFound" value="true" /&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;value&gt;classpath:application.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;context:component-scan base-package="org.sales.dao.Impl" /&gt; &lt;!-- 数据源配置,使用应用内的DBCP数据库连接池 --&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;!-- Connection Info --&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="namingStrategy"&gt; &lt;bean class="org.hibernate.cfg.ImprovedNamingStrategy" /&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;${hibernate.show_sql}&lt;/prop&gt; &lt;prop key="hibernate.format_sql"&gt;${hibernate.format_sql}&lt;/prop&gt; &lt;prop key="hibernate.cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/prop&gt; &lt;!-- &lt;prop key="hibernate.cache.provider_configuration_file_resource_path"&gt;${hibernate.ehcache_config_file}&lt;/prop&gt;--&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="packagesToScan" value="org.sales.entity" /&gt; &lt;property name="annotatedClasses"&gt; &lt;list&gt; &lt;value&gt;org.sales.entity.Iteminfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Cardinfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Positioninfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Sellinfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Userinfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Voteinfo&lt;/value&gt;&lt;/list&gt; &lt;/property&gt;&lt;/bean&gt; &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" &gt; &lt;property name="sessionFactory" ref="sessionFactory"/&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;bean id="CardinfoDAO" class="org.sales.entity.CardinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="IteminfoDAO" class="org.sales.entity.IteminfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="PositioninfoDAO" class="org.sales.entity.PositioninfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="SellinfoDAO" class="org.sales.entity.SellinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="UserinfoDAO" class="org.sales.entity.UserinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="VoteinfoDAO" class="org.sales.entity.VoteinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <br /><strong>web.xml</strong> <br /><pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath*: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.hibernate3.support.OpenSessionInViewFilter&lt;/filter-class&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;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;filter&gt; &lt;filter-name&gt;struts2Filter&lt;/filter-name&gt; &lt;filter-class&gt;org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2Filter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;OpenSessionInViewFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </pre> <br /> <br />结果在LoginAction.java里面输出: <br />id:null <br />username:username <br />password:USERNAME <br />error <br />说明: error是当被注入的属性为空的时候输出. <br /> 求解~ <br /> <br /><strong>异常(网页上的):</strong> <br />HTTP Status 500 - <br /> <br />type Exception report <br /> <br />message <br /> <br />description The server encountered an internal error () that prevented it from fulfilling this request. <br /> <br />exception <br /> <br />java.lang.NullPointerException <br /> org.sales.actions.LoginAction.login(LoginAction.java:53) <br /> sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) <br /> sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) <br /> sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) <br /> java.lang.reflect.Method.invoke(Method.java:597) <br /> com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) <br /> com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) <br /> com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div">有异常吗。<br /> <br />敢不敢把异常发出来看一下。</div><br />发了<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div">好吧,应该不需要异常,请把ACTION里定义的DAO的变量名,变得和xml里定义的BEAN ID属性一致。</div><br />xml里面没有对应的bean,因为使用注释<br/><strong>问题补充</strong><br/><div class="quote_title">yyf365 写道</div><div class="quote_div">可能和楼主的应用写法不太相同,请问你其他的service是否能注入成功呢?,不过是否能试试在applicationContext配置文件中的声明方式换一种呢?<br /><br />如:<br />&lt;bean id="UserInfoDAO"<br /> class="UserInfoDAOImp"&gt;<br /> &lt;/bean&gt;<br />这种形式注入,实例化由spring托管,而在action中只对UserInfoDAO的service进行注入呢<br /><br />而如果出了该service无法注入外,其他其余的service都能正常注入使用,那就另想办法了</div><br /> 可是这种方法有点麻烦,我想实现注释注入,xml文件里面有个扫描的:<br /> &lt;context:component-scan base-package="org.sales.dao.Impl" /&gt;&nbsp; <br/><strong>问题补充</strong><br/>已经试过在 <strong>applicationContext.xml</strong> 文件里面添加<br /><pre name="code" class="xml">&lt;bean id="userInfoDAOImpl" class="org.sales.dao.Impl.UserInfoDAOImpl"&gt; &lt;/bean&gt; &lt;bean id="loginAction" class="org.sales.actions.LoginAction"&gt; &lt;property name="userInfoDAOImpl"&gt; &lt;ref bean="userInfoDAOImpl" /&gt; &lt;/property&gt; &lt;/bean&gt;</pre><br /><br />异常信息一样.<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div"><div class="quote_title">bbinglongg 写道</div><div class="quote_div"><div class="quote_title">xixix2004 写道</div><div class="quote_div">好吧,应该不需要异常,请把ACTION里定义的DAO的变量名,变得和xml里定义的BEAN ID属性一致。</div><br />xml里面没有对应的bean,因为使用注释</div><br /><br /><br />你完全没看懂我在说什么。<br /><br /><pre name="code" class="java">private UserInfoDAO userinfoDAO; </pre><br /><pre name="code" class="java"> &lt;bean id="userinfoDAO" class="org.sales.entity.UserinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; </pre><br /><br /><br /><br /></div><br />在它上面有一句:<br /><pre name="code" class="java">@Autowired</pre><br />是自动注入的意思<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div">&lt;ref bean="UserInfoDAO" /&gt;这里的REF的BEAN, 写你之前定义的BEAN的ID。你可明白?</div><br />明白<br/><strong>问题补充</strong><br/><div class="quote_title">dwbin 写道</div><div class="quote_div">loginAction没有进行spring托管。<br />这个类spring不会自己进行注入的。你的ssh整合有问题</div><br /><br />那我应该怎么修改呢?<br/><strong>问题补充</strong><br/><div class="quote_title">dwbin 写道</div><div class="quote_div">loginAction没有进行spring托管。<br />这个类spring不会自己进行注入的。你的ssh整合有问题</div><br />在 <pre name="code" class="java">@Autowired</pre> 这个标签里面已经是注入了
SSH总报Orders表不存在
[b]小弟使用struts2.1.6+Spring2.5+hibernate3.3做了一个项目,在本地Windows上正常,由于项目要在Linux上运行,日志总报以下错误:[/b] :cry: [code="java"] 2009-11-16 10:03:11,307 WARN [org.hibernate.util.JDBCExceptionReporter] - SQL Error: 1146, SQLState: 42S02 2009-11-16 10:03:11,308 ERROR [org.hibernate.util.JDBCExceptionReporter] - Table 'shop.Orders' doesn't exist 2009-11-16 10:03:11,308 ERROR [com.shop.common.dao.implay.BaseDAOImplay] - 查询出错了!! org.hibernate.exception.SQLGrammarException: could not execute query at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.loader.Loader.doList(Loader.java:2235) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312) at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723) at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165) at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175) at com.shop.common.dao.implay.BaseDAOImplay$4.doInHibernate(BaseDAOImplay.java:285) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419) at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:339) at com.shop.common.dao.implay.BaseDAOImplay.findSQL(BaseDAOImplay.java:275) at com.shop.order.dao.implay.OrdersDAOImplay.findOrderStatusNumDAO(OrdersDAOImplay.java:112) at com.shop.order.service.implay.OrderServiceImplay.findOrderStatusNumService(OrderServiceImplay.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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'shop.Orders' doesn't exist 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 com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3515) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3447) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1951) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2101) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2554) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1761) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1912) at sun.reflect.GeneratedMethodAccessor145.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.logicalcobwebs.proxool.ProxyStatement.invoke(ProxyStatement.java:100) at org.logicalcobwebs.proxool.ProxyStatement.intercept(ProxyStatement.java:57) at $java.sql.Wrapper$$EnhancerByProxool$$19d445f0.executeQuery(<generated>) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1812) at org.hibernate.loader.Loader.doQuery(Loader.java:697) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) ... 104 more [/code] [b]但是数据都能查询出来,原来名字起的是order,后来与SQL的关键字冲突,就在后面加了个s,现在变成数据能查出来,就是这个错误,而且在本地Windows上正常,Linux不正常,请大侠们指点一下.[/b] [b]问题补充:[/b] [color=orange][b]我把数据库中的改成大小的. 它提示我 Table 'shop.orders' doesn't exist 刚好和开始的不一样了,并且查询不到结果.. 报的错误是一样的.. 这个问题大家遇到过吗?虽然结果能查询出来,但是它老报找不到表,好烦人的.[/b][/color]
getHibernateTemplate()为NUll,困扰好几天了,网上也找了好些方法一直解决不掉
小弟刚刚开始学SSH,是用的Struts2+Hibernate+Spring,运行的时候发现getHibernateTemplate()得到的模板类始终是nUll值,郁闷好几天了,一直在我网上试各种方法,迄今任为解决,恳请各位指教咯! [size=large][b]applicationContext.xml:([/b]事务处理这儿没贴出来)[/size] [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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <!-- 定义数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/jjufriend"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 定义Hibernate的sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- Hibernate 的sessionFactory的属性 --> <property name="hibernateProperties"> <props> <!-- 数据库方言 --> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <!-- 显示Hibernate持久化操作所生成的SQL语句 --> <prop key="hibernate.show_sql">true</prop> <!-- 将SQL脚本进行格式化后再输出 --> <prop key="hibernate.format_sql">true</prop> </props> </property> <!-- 列出全部的映射文件 --> <property name="mappingResources"> <list> <value>com/jjufriend/student/model/Student.hbm.xml</value></list> </property></bean> <!-- 配置dao组件 --> <bean id="studentDao" class="com.jjufriend.student.dao.impl.StudentDaoHibernate"> <!-- 依赖注入DAO组件所必需的SessionFactory引用 --> <property name="sessionFactory" ref="sessionFactory"> </property> </bean> <!-- 配置业务逻辑组件 --> <bean id="mgr" class="com.jjufriend.student.service.impl.StudentManagerImpl"> <property name="studentDao" ref="studentDao"></property> </bean> [/code] [size=large]studentDao.java:[/size] [code="java"]package com.jjufriend.student.dao; import java.util.List; import com.jjufriend.student.model.Student; public interface StudentDao { Student get(Integer id); Integer save(Student student); void update(Student student); void delete(Student student); void delete(Integer id); List<Student> findAll(); Student findStudentByNameAndPass(String username,String password); Student findByName(String username); }[/code] [size=large]StudentDaoHibernate.java:[/size] [code="java"]package com.jjufriend.student.dao.impl; import java.io.Serializable; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.jjufriend.student.dao.StudentDao; import com.jjufriend.student.model.Student; public class StudentDaoHibernate extends HibernateDaoSupport implements StudentDao,Serializable { private SessionFactory sessionFactory; HibernateTemplate ht = this.getHibernateTemplate() ; public void delete(Student student) { // TODO Auto-generated method stub getHibernateTemplate().delete(student); } public void delete(Integer id) { // TODO Auto-generated method stub getHibernateTemplate().delete(get(id)); } public List<Student> findAll() { // TODO Auto-generated method stub return (List<Student>)getHibernateTemplate().find("from Student"); } public Student findByName(String username) { List stu = getHibernateTemplate().find("from Student st where st.username = ?",username); if(stu != null && stu.size() >= 1){ return (Student)stu.get(0); } return null; } public Student findStudentByNameAndPass(String username, String password) { // TODO Auto-generated method stub List students = null; try{ // HibernateTemplate temple = this.getHibernateTemplate(); System.out.println("模板类是否为NULL>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ht); // 取出所有 students = temple.find("from student"); students = ht.find("from student st where st.username = " + username + " and st.password = " + password); }catch(Exception e){ System.out.println("查找过程中出现异常.............."); e.printStackTrace(); } if(students != null && students.size() >= 1){ return (Student)students.get(0); } return null; } public Student get(Integer id) { return (Student)getHibernateTemplate().get(Student.class, id); } public Integer save(Student student) { return (Integer)getHibernateTemplate().save(student); } public void update(Student student) { // TODO Auto-generated method stub getHibernateTemplate().update(student); } } [/code] [size=large]StudentManager.java:[/size] [code="java"]package com.jjufriend.student.service; import com.jjufriend.student.model.Student; public interface StudentManager { int addStudent(Student student) throws Exception; int loginValid(Student student) throws Exception; boolean validateName(String username) throws Exception; } [/code] [size=large]StudentManagerImpl.java:[/size] [code="java"]package com.jjufriend.student.service.impl; import com.jjufriend.student.dao.StudentDao; import com.jjufriend.student.dao.impl.StudentDaoHibernate; import com.jjufriend.student.model.Student; import com.jjufriend.student.service.StudentManager; public class StudentManagerImpl implements StudentManager { /*2009-11-12 22:44修改 出去new StudentDaoHibernate() */ private StudentDao studentDao = new StudentDaoHibernate() ; // private ApplicationContext cxt = // new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); // studentDao =(StudentDaoHibernate)cxt.getBean("studentDao"); public void setStudentDao(StudentDao studentDao){ this.studentDao = studentDao ; } public int addStudent(Student student) throws Exception { // TODO Auto-generated method stub try{ studentDao.save(student); return student.getId(); }catch(Exception e){ e.printStackTrace(); throw new Exception("新增用户时出现异常"); } } public int loginValid(Student student) throws Exception { try{ System.out.println(studentDao); System.out.println("是否取到页面提交的数据:Name="+student.getUsername()); Student stu = studentDao.findStudentByNameAndPass(student.getUsername(), student.getPassword()); if(stu != null ){ return stu.getId(); } }catch(Exception e){ System.out.println("验证用户登录时出现异常"); e.printStackTrace(); } // TODO Auto-generated method stub return -1; } public boolean validateName(String username) throws Exception { // TODO Auto-generated method stub try{ if (studentDao.findByName(username) != null){ return true ; } }catch(Exception e){ System.out.println("验证用户名是否用效时出错"); e.printStackTrace(); } return false ; } } [/code] 问题的关键是通过方法getHibernateTemplate()不能正确得到HibernateTemplate对象,始终的空值,网上有很多解决的办法,差不多我都试过了, 下面这种方法是说不能直接new StudentDao对象,用下面这种方法取得,可以启动服务器老是不停地跳动,一直不停,直到报错。 [code="java"] // private ApplicationContext cxt = // new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); // private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao");[/code] 还有些方法是直接从applicationContext.xml中的bean取得HibernateTemplate对象,始终都搞不定,望大家指教了。 [size=medium](顶格的System.out.println()语句均是测试用的语句)[/size] [b]问题补充:[/b] 谢谢大家的热心帮助!! 确实其中出了不少问题,主要是最近网上看到解决这个方法的帖子很多,尝试过很多方法,都有点儿改晕了。 一楼的方法我尝试了,还是不行,[code="java"] private ApplicationContext cxt = this.getApplicationContext(); private StudentDao studentDao = (StudentDaoHibernate)cxt.getBean("studentDao"); [/code] 其中那个this.getApplicationContext(); 方法根本不存在啊,无法取得配置文件。 之前类似的方法我也用过就是用[code="java"] private ApplicationContext cxt = new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao"); [/code]取得,但是当启动服务器后,后台一直跑个不停,仿佛是个死循环似的。浏览器中通过http://localhost:8080访问都无效! StudentDaoHibernate.java中的private SessionFactory sessionFactory;已经去掉 数据库方言也该过来了
整合Spring+SpringMVC+Hibernate时,无法进入控制层
整合Spring+SpringMVC+Hibernate时,启动正常,可以打开登录页面,但是进行登录时,无法进入controller层,而且不报错,只输出三行日志。 DispatcherServlet with name 'springMVC' processing POST request for [/SSH/user/login.do] No mapping found for HTTP request with URI [/SSH/user/login.do] in DispatcherServlet with name 'springMVC' Successfully completed request 意思大概是找不到路径,但应该不是路径的问题,如果路径有问题,页面上message会显示有问题的路径,而不是什么都没有。 HTTP Status 404 - type Status report message description The requested resource is not available. Apache Tomcat/7.0.82 spring-context.xml配置是这样的 <!-- 自动扫描 --> <context:component-scan base-package="service,dao,entity,controller"/> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" > <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="url" value="jdbc:sqlserver://localhost:1433;database=user_role" /> <property name="username" value="sa"/> <property name="password" value="123456"/> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> <!--指定数据库方言--> <prop key="hibernate.hbm2ddl.auto">update</prop> <!--hibernate根据实体自动生成数据库表--> <prop key="hibernate.show_sql">true</prop> <!--在控制台显示执行的数据库操作语句--> <prop key="hibernate.format_sql">true</prop> <!--在控制台显示执行的数据库操作语句(格式)--> </props> </property> <property name="annotatedClasses"> <list> <value>entity</value> </list> </property> </bean> <!-- <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="userDao" class ="dao.UserDao"> <property name="sessionFactory" ref="sessionFactory" /> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> --> <!-- 开启注解事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 事物管理器配置 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置事务,使用代理的方式 --> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-myException</prop> <prop key="del*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> spring-mvc.xml配置 <!-- 开启注解 --> <mvc:annotation-driven /> <!-- 注解扫描包 --> <context:component-scan base-package="controller" /> <!-- 静态资源(js/image)的访问 --> <mvc:resources location="/js/" mapping="/js/**"/> <!-- 定义视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> web配置 <display-name>SSH</display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <!-- 加载所有的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-context.xml</param-value> </context-param> <!-- 配置Spring监听 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- 配置SpringMVC --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置字符集 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 如果OpenSession加了*号,启动时会报错,找不到名为sessionFactory的bean --> <!-- 配置Session --> <filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>/</url-pattern> </filter-mapping>
对充血模型的疑问
小弟我在坛子上看到关于贫血模型和充血模型的讨论后一直再想这对于我这种代码小工意味着啥? <br />是否可以更快更迅速更敏捷的完成代码完成开发。 <br />一直做的项目都是SSH 然后分层 action,service,dao,entity;有时候我觉得dao层没什么必要啊,既然 <br />hibernate是面向对象为何还要 dao.save(entity)&nbsp;&nbsp; dao.update(entity) 这样操作? <br />感觉如果去掉dao层 直接entity.update(),entity.delete();&nbsp; 这样是否会更形象? <br />然后小弟开始尝试,首先搭了个struts2+spring3+Hibernate3.6的ssh工程用的是全注解搭法这样开发就不用写配置文件了还是相当的爽啊 <br /> <br />首先我觉得应该有一个公共的类充当所有entity的父类 <br /><pre name="code" class="java"> import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.beans.BeanUtils; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Repository; @Repository("MagicH") public class MagicH extends HibernateTemplate { @Resource(name = "sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } private Serializable id; // 标示 private Class clazz; // 实体 private Object entity; // 数据库实体 private PropertyDescriptor targetPds[]; //初始化后属性 private HashMap setMethodMap = new HashMap(); //set方法映射 private HashMap getMethodMap = new HashMap(); //get方法映射 /** * 模型初始化 * * @param clazz * @param id */ public boolean init(Class clazz, Serializable id) { this.id = id; this.clazz = clazz; PropertyDescriptor targetPds[] = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor pdObj : targetPds) { setMethodMap.put(pdObj.getName().toLowerCase(), pdObj.getWriteMethod()); getMethodMap.put(pdObj.getName().toLowerCase(), pdObj.getReadMethod()); } this.entity = get(clazz, id); return this.entity==null?false:true; } /** * 获取对象实体 * * @return */ public Object getObj() { if (entity == null) { this.entity = get(clazz, id); } return entity; } /** * 删除对象实体 */ public void delObj() { if (entity != null) delete(entity); else delete(get(clazz, id)); } /** * 设置数据库实体属性 * @param propertyName * @param propertyValue */ public void setProperty(String propertyName, Object propertyValue) { Method writeMethod = (Method) setMethodMap.get(propertyName.toLowerCase()); try { writeMethod.invoke(entity, new Object[] {propertyValue}); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 获取属性的值 * @param propertyName * @return */ public Object getPropertyValue(String propertyName) { Method readMethod = (Method)getMethodMap.get(propertyName.toLowerCase()); Object returnValue = null; try { returnValue = readMethod.invoke(entity,null); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnValue; } /** * 更新对象 */ public void updateObj() { update(entity); } /** * 保存对象 * @param obj * @return */ public Serializable addObj(Object obj) { Serializable id = save(obj); init(obj.getClass(),id); return id; } } </pre> <br /> <br />建立一张用户表测试,对应实体如下 <br /><pre name="code" class="java"> import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.springframework.stereotype.Repository; import com.usoft.core.dao.impl.MagicH; /** * MagicUser entity. @author MyEclipse Persistence Tools */ @Repository("MagicUser") @Entity @Table(name = "MAGIC_USER") public class MagicUser extends MagicH implements java.io.Serializable { // Fields private String userId; private String userNam; private String userSex; private String userPhone; // Constructors /** default constructor */ public MagicUser() { } /** full constructor */ public MagicUser(String userNam, String userSex, String userPhone) { this.userNam = userNam; this.userSex = userSex; this.userPhone = userPhone; } // Property accessors @GenericGenerator(name = "generator", strategy = "uuid.hex") @Id @GeneratedValue(generator = "generator") @Column(name = "USER_ID", unique = true, nullable = false, length = 32) public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } @Column(name = "USER_NAM", length = 500) public String getUserNam() { return this.userNam; } public void setUserNam(String userNam) { this.userNam = userNam; } @Column(name = "USER_SEX", length = 1) public String getUserSex() { return this.userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } @Column(name = "USER_PHONE", length = 11) public String getUserPhone() { return this.userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } } </pre> <br /> <br />这是本人测试用的service <br /><pre name="code" class="java"> import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.usoft.magich.bs.ImagicServiceTest; import com.usoft.magich.vo.MagicUser; @Service("MagicService") @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public class MagicServiceTestImpl implements ImagicServiceTest { @Resource private MagicUser magicUser; public void testMagicH() { //保存 magicUser.setUserNam("用户123"); magicUser.setUserPhone("12345"); magicUser.setUserSex("1"); magicUser.addObj(magicUser); //更新 magicUser.setProperty("UserNam", "1234567"); magicUser.updateObj(); System.out.print(magicUser.getPropertyValue("UserNam")); boolean b1 = magicUser.init(magicUser.getClass(), "aaa"); //id 不存在初始化失败 System.out.println(b1); boolean b2 = magicUser.init(magicUser.getClass(),"402881862da6ec3b012da6fb4f640004"); //id存在为 true System.out.println(b2); magicUser.delObj(); //删除 对象 } } </pre> <br /> <br />只是中午吃饭时脑子那么想了一下,然后回来就尝试写了个单表的增删改查,我个人举得无论是单表还是多表最后数据库查出来的无非是个二叉表,而其中的一条记录应该对应一个java类 多条记录则是该java类的List集合,然后所有的数据库操作不再是dao.doSomething 而是entity.doSomething <br />我这样做了后写的代码就只有actiong,service,entity层了,不知道这样是否可行,谁能解释一下我的疑问。 <br /> <br /><br/><strong>问题补充</strong><br/>看了大家的回复深受启发,感觉自己这个想法似乎不可取就不再钻牛角尖了。 <br />可能一直处于开发人员的角色,所以关系的核心问题无非就是 写最少的代码做最多的事
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
剑指Offer对答如流系列 - 重建二叉树
面试题6:重建二叉树 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出图2.6所示的二叉树并输出它的头结点。二叉树结点的定义如下: class TreeNode{ int val; TreeNode l...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
一份王者荣耀的英雄数据报告
咪哥杂谈本篇阅读时间约为 6 分钟。1前言前一阵写了关于王者的一些系列文章,从数据的获取到数据清洗,数据落地,都是为了本篇的铺垫。今天来实现一下,看看不同维度得到的结论。2环境准备本次实...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
为什么程序猿都不愿意去外包?
分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助
Java校招入职华为,半年后我跑路了
何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...
立即提问