spring整合hibernate后怎么获取spring JdbcTemplate 5C

目前有两种情况:
1、图片说明图片说明图片说明通过配置sring的DataSource,然后引用ref,最后代码里面getBean三部确实可以获取到,但是这样子的话spring就不读取hibernate.cfg.xml,相当于舍弃了hibernate.cfg.xml,但是我还是想用,我想把applicationContext.xml和hibernate.cfg.xml分开配置,不要写在一起。
2、后来有一种方法读取hibernate.cfg.xml配置(即使用hibernate自带的xml配置)图片说明然后获取SessionFactory图片说明但是这样子的话无法获取JdbcTemplate了,因为看了JdbcTemplate源代码,必须要设置DataSource,而SessionFactory里面没有DataSource,请教各路大佬要保留hibernate.cfg.xml又要JdbcTemplate要怎么做?

2个回答

都用spring hibernate了,不用第三方数据库连接池吗,不用spring来管理事务吗?
再说了 session.createNativeQuery 完全可以替换JdbcTemplate 来实现相关功能。

你这做法欠妥。

qq_16127313
爱码少年 https://gitee.com/00fly/java-code-frame/blob/master/springmvc-hbn/src/test/java/com/fly/test/QueryTest.java
大约一年之前 回复
helloselang92
hello涩郎 大佬,我这个是hibernate4.3.9,没有session.createNativeQuery,大佬的建议是舍弃hibernate.cfg.xml,而是全部写到spring里面去,统一用spring去管理?
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring mvc 整合hibernate 菜鸟级问题
小弟想用spring mvc 整合hibernate 但是spring总是如法注入。 spring配置文件如下 [code="java"] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="jdbcPropertyConfiger" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass"> <value>${datasource.driverClassName}</value> </property> <property name="jdbcUrl"> <value>${datasource.url}</value> </property> <property name="user"> <value>${datasource.username}</value> </property> <property name="password"> <value>${datasource.password}</value> </property> <property name="acquireIncrement"> <value>${c3p0.acquireIncrement}</value> </property> <property name="initialPoolSize"> <value>${c3p0.initialPoolSize}</value> </property> <property name="minPoolSize"> <value>${c3p0.minPoolSize}</value> </property> <property name="maxPoolSize"> <value>${c3p0.maxPoolSize}</value> </property> <property name="maxIdleTime"> <value>${c3p0.maxIdleTime}</value> </property> <property name="idleConnectionTestPeriod"> <value>${c3p0.idleConnectionTestPeriod}</value> </property> <property name="maxStatements"> <value>${c3p0.maxStatements}</value> </property> <property name="numHelperThreads"> <value>${c3p0.numHelperThreads}</value> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <props> <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mappingResources"> <list> <value>classpath:ac02.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="QscDBService" class ="com.qsc.m.QscDBServiceImpl"> <property name="sessionFactory" ref="sessionFactory" /> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> <bean id="ControllerJoin" class="com.qsc.c.ControllerJoin"> <property name="QscDBService" ref="QscDBService"></property> </bean> </beans> [/code] QscDBservice类如下 [code="java"] package com.qsc.m; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.orm.hibernate3.HibernateTemplate; import com.qsc.pojo.ac02; public class QscDBServiceImpl extends JdbcTemplate implements QscDBService { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public void sava(ac02 ac02) { hibernateTemplate.save(ac02); } [/code] ControllerJoin类如下 [code="java"] package com.qsc.c; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import com.qsc.m.QscDBService; import com.qsc.pojo.ac02; import com.qsc.spring.ContextLoaderListener; public class ControllerJoin implements Controller { private QscDBService qsc; public QscDBService getQsc() { return qsc; } public void setQsc(QscDBService qsc) { this.qsc = qsc; } public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { //final QscDBService qsc = (QscDBService)ContextLoaderListener.getBean("QscDBService"); ac02 ac02 = new ac02(); String aac001 = arg0.getParameter("account"); String aac002 = arg0.getParameter("name"); String aac003 = arg0.getParameter("age"); String aac004 = arg0.getParameter("email"); String aac005 = arg0.getParameter("phone"); String aac006 = arg0.getParameter("pass"); ac02.setAac001(aac001); ac02.setAac002(aac002); ac02.setAac003(Integer.parseInt(aac003)); ac02.setAac004(aac004); ac02.setAac005(aac005); ac02.setAac006(aac006); qsc.sava(ac02); return new ModelAndView("success"); } } [/code] debug后发现 qsc和hibernatetemplate 这两个全是null 说明spring没注入成功,这是为啥啊? 谢谢
spring jdbcTemplate怎么得到新插入数据的主键(varchar2类型)
在网上看到用KeyHelper 可以得到数字类型的主键,但是表的主键guid是varchar类型的,用Spring的jdbcTemplate有什么方法可以得到新插入数据的主键? 用的是Hibernate 数据库是Oracle 求大神帮忙了啊! 不用先插入了,再查询的方法怎么破?
在Spring MVC框架下 一个@Repository的dao中 可以同时注入hibernateTemplate和jdbcTemplate吗
在Spring MVC框架下 一个@Repository的dao中 因为感觉jdbc查询起来编码比较方便 所有想引入spring jdbc的东西 这时一个dao中想同时注入hibernateTemplate和jdbcTemplate 这样做可以吗 存在什么潜在的问题吗? 配置XML文件 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}"/> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.max_fetch_depth">3</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.jdbc.fetch.size">50</prop> <prop key="hibernate.jdbc.batch_size">50</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> </props> </property> <property name="mappingDirectoryLocations" value="classpath:/org/abrs/kt/hbm"/> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" p:sessionFactory-ref="sessionFactory"/> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource"/> 基类dao public class BaseScDao<T>{ private Class<T> entityClass; @Autowired private HibernateTemplate hibernateTemplate; @Autowired private JdbcTemplate jdbcTemplate; **** } 继承dao @Repository public class PcMainDao extends BaseScDao<PcMain> { public PcMain queryByYear(int year){ List<PcMain> list = (List<PcMain>)getHibernateTemplate().find("from PcMain pm where pm.Year=?", year); if(list.size()!=0){ PcMain bean = list.iterator().next(); return bean; }else{ return null; } } public String queryEndTimeByYear(int year){ String endTime = getJdbcTemplate().queryForObject("select endTime from pc_main where year=?", String.class, year); return endTime; } } 请大师指导下 谢啦!
springboot整合hibernate 运行时重复报错对象名 'SPRING_SESSION' 无效?
13:12:00 [pool-3-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Opened new EntityManager [SessionImpl(1764884484<open>)] for JPA transaction 13:12:00 [pool-3-thread-1] DEBUG o.h.e.t.internal.TransactionImpl - On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false 13:12:00 [pool-3-thread-1] DEBUG o.h.e.t.internal.TransactionImpl - begin 13:12:00 [pool-3-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@6512beb1] 13:12:00 [pool-3-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL update 13:12:00 [pool-3-thread-1] DEBUG o.s.jdbc.core.JdbcTemplate - Executing prepared SQL statement [DELETE FROM SPRING_SESSION WHERE EXPIRY_TIME < ?] 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.xml.XmlBeanDefinitionReader - Loaded 11 bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml] 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'DB2' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'Derby' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'H2' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'HDB' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'HSQL' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'Informix' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'MS-SQL' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'MySQL' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'Oracle' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'PostgreSQL' 13:12:00 [pool-3-thread-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating shared instance of singleton bean 'Sybase' 13:12:00 [pool-3-thread-1] DEBUG o.s.j.support.SQLErrorCodesFactory - Looking up default SQLErrorCodes for DataSource [com.zaxxer.hikari.HikariDataSource@18e4af8d] 13:12:00 [pool-3-thread-1] DEBUG o.s.j.support.SQLErrorCodesFactory - SQL error codes for 'Microsoft SQL Server' found 13:12:00 [pool-3-thread-1] DEBUG o.s.j.support.SQLErrorCodesFactory - Caching SQL error codes for DataSource [com.zaxxer.hikari.HikariDataSource@18e4af8d]: database product name is 'Microsoft SQL Server' 13:12:00 [pool-3-thread-1] DEBUG o.s.j.s.SQLErrorCodeSQLExceptionTranslator - Translating SQLException with SQL state 'S0002', error code '208', message [对象名 'SPRING_SESSION' 无效。]; SQL was [DELETE FROM SPRING_SESSION WHERE EXPIRY_TIME < ?] for task [PreparedStatementCallback] 13:12:00 [pool-3-thread-1] DEBUG o.s.t.support.TransactionTemplate - Initiating transaction rollback on application exception org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [DELETE FROM SPRING_SESSION WHERE EXPIRY_TIME < ?]; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: 对象名 'SPRING_SESSION' 无效。 at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:234) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1444) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:632) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:862) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:917) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.lambda$cleanUpExpiredSessions$7(JdbcOperationsSessionRepository.java:616) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.cleanUpExpiredSessions(JdbcOperationsSessionRepository.java:615) at org.springframework.session.jdbc.config.annotation.web.http.JdbcHttpSessionConfiguration.lambda$configureTasks$0(JdbcHttpSessionConfiguration.java:213) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: 对象名 'SPRING_SESSION' 无效。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:259) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1547) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:548) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:479) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7344) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2713) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:224) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:204) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:426) at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:867) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:617) ... 16 common frames omitted 13:12:00 [pool-3-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Initiating transaction rollback 13:12:00 [pool-3-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Rolling back JPA transaction on EntityManager [SessionImpl(1764884484<open>)] 13:12:00 [pool-3-thread-1] DEBUG o.h.e.t.internal.TransactionImpl - rolling back 13:12:00 [pool-3-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Closing JPA EntityManager [SessionImpl(1764884484<open>)] after transaction 13:12:00 [pool-3-thread-1] ERROR o.s.s.s.TaskUtils$LoggingErrorHandler - Unexpected error occurred in scheduled task. org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [DELETE FROM SPRING_SESSION WHERE EXPIRY_TIME < ?]; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: 对象名 'SPRING_SESSION' 无效。 at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:234) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1444) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:632) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:862) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:917) at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.lambda$cleanUpExpiredSessions$7(JdbcOperationsSessionRepository.java:616) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140) at org.springframework.session.jdbc.JdbcOperationsSessionRepository.cleanUpExpiredSessions(JdbcOperationsSessionRepository.java:615) at org.springframework.session.jdbc.config.annotation.web.http.JdbcHttpSessionConfiguration.lambda$configureTasks$0(JdbcHttpSessionConfiguration.java:213) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: 对象名 'SPRING_SESSION' 无效。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:259) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1547) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:548) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:479) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7344) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2713) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:224) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:204) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:426) at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:867) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:617) ... 16 common frames omitted 13:12:18 [HikariPool-1 housekeeper] DEBUG com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Pool stats (total=10, active=0, idle=10, waiting=0)
spring+hibernate游标不释放问题
系统使用spring+hibernate连接池与spring事务设置如下: [code="java"] <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="jdbcUrl"> <value>jdbc:oracle:thin:@192.168.1.106:1521:orcl</value> </property> <property name="user"> <value>wjcx</value> </property> <property name="password"> <value>wjcx</value> </property> <!--连接池中保留的最小连接数。--> <property name="minPoolSize"> <value>5</value> </property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize"> <value>30</value> </property> <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize"> <value>10</value> </property> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime"> <value>60</value> </property> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement"> <value>5</value> </property> <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0--> <property name="maxStatements"> <value>0</value> </property> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod"> <value>60</value> </property> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts"> <value>30</value> </property> <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false--> <property name="breakAfterAcquireFailure"> <value>true</value> </property> <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 等方法来提升连接测试的性能。Default: false --> <property name="testConnectionOnCheckout"> <value>false</value> </property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.cache.provider_class">com.jweb.common.cache.OSCacheProvider</prop> <prop key="hibernate.cache.use_query_cache">false</prop> </props> </property> </bean> <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="baseTxProxy" abstract="true" lazy-init="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> <property name="transactionAttributes"> <props> <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="list*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="edit*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="create*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property> </bean> [/code] dao中的代码如下 [code="java"] public List getListByArticle(ArticleModel article, String orderby, int firstResult, int maxResults,String tid) { String hql = "from UserModel"; Session session = this.getSession(); Query query = session.createQuery(hql); query.setFirstResult(firstResult); query.setMaxResults(maxResults); return query.list(); } [/code] 里面有很多如上面的方法:但系统运行一段时间后总是游标超出最大值!因为用了spring事务,service类中没有关闭连接.但不知道为什么游标老是超出,希望有人解答! [b]问题补充:[/b] 程序有些地方使用了HibernateTemplate这个,但因为存在一些复杂SQL的组装只想知道上面这种写法会不会关掉游标的. [b]问题补充:[/b] 不是使用spring的事务管理就不用关连接吗 [b]问题补充:[/b] 发现添加了session.close();系统后就会报得不到session了!象上面这种写法有什么补求的办法吗?因为代码已经写了很多了!
Spring集成Hibernate4报不能打开连接
错误信息: org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) at com.sun.proxy.$Proxy7.addStudent(Unknown Source) at action.StudentAction.execute(StudentAction.java:22) at test.RunTest.main(RunTest.java:34) Caused by: org.hibernate.exception.GenericJDBCException: Could not open connection at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:221) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157) at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:427) at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450) ... 9 more Caused by: java.sql.SQLException: 调用中无效的参数 at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:147) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:209) at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236) at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:454) at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165) at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35) at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:802) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:130) at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141) at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:301) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214) ... 12 more 配置文件: <?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <context:component-scan base-package="entity"></context:component-scan> <bean name="prop" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:datasource.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url"><value>jdbc:oracle:thin:@localhost:1521:orcl</value></property> <property name="username" value="lei" /> <property name="password" value="lei" /> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"><ref bean="dataSource"></ref></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!--<property name="configLocation"> <value>hibernate.cfg.xml</value></property> --> <property name="dataSource"> <ref bean="dataSource"/></property> <property name="mappingLocations" value="entity/*.hbm.xml"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!-- 事务管理器--> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" > <ref bean="sessionFactory" /> </property> </bean> <!-- 事务代理 --> <bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true"> <!-- 配置事务管理器 --> <property name="transactionManager" ref="transactionManager" /> <!-- 配置事务属性 --> <property name="transactionAttributes"> <props> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> </props> </property> </bean> <!-- 配置DAO --> <bean id="searchDao" class="dao.SearchDao"> <property name="sessionFactory" ref="sessionFactory" /> <!-- <property name="jdbcTemplate" ref="jdbcTemplate" /> --> </bean> <bean id="updateDao" class="dao.UpdateDao"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置Service --> <bean id="studentServiceTX" class ="serviceImpl.StudentServiceImpl" > <property name="searchDao" ref="searchDao" /> <property name="updateDao" ref="updateDao" /> </bean> <bean id="studentService" parent="transactionBase" > <property name="target" ref="studentServiceTX" /> </bean> <!-- <bean id="studentService" class ="serviceImpl.StudentServiceImpl" > <property name="searchDao" ref="searchDao" /> </bean> --> <!-- 配置Action --> <bean id="studentAction" class ="action.StudentAction" > <property name="studentService" ref="studentService" /> </bean> </beans> Dao代码: package dao; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.hibernate.Transaction; import org.springframework.orm.hibernate4.HibernateTemplate; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import entity.StudentInfo; public class SearchDao{ private JdbcTemplate jdbcTemplate; private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public SearchDao(){ super(); } @SuppressWarnings("unchecked") public void addStudent(StudentInfo student)throws Exception { HibernateTemplate hibernateTemplate = new HibernateTemplate(this.sessionFactory); hibernateTemplate.save(student); } } 请教各位大神
spring+hibernate 在oracle经常出现未提交的事务
<p><br><br>错误描述:系统在运行一个不定的时间后,在数据库中会产生一个未提交的事务,经查访问 <br>日志,通常是在添加或更新操作时产生的,该事务所在的连接被其他线程使用后,会导致其他数据 <br>库操作都被阻塞,最终导致系统无法访问。该错误经开发人员手动测试和压力测试都未能重现,数 <br>据均能正常提交,而且在多个dao中都会出现。 <br><br><br>系统环境: <br>redhat5,oracle10,jdk1.6,tomcat6,spring2,hibernate3,dbcp <br><br>以下是某个Dao的典型代码及配置 <br>public class BaseDAO { <br><br>public final int RESULT_FETCH_SIZE=100; <br>protected DataSource dataSource = null; <br>protected SessionFactory sessionFactory = null; <br>    protected HibernateTemplate ht = null; <br>    protected JdbcTemplate jt = null; <br><br>    public void setSessionFactory(SessionFactory factory) <br>    { <br>        sessionFactory = factory; <br>        ht  = new HibernateTemplate(sessionFactory); <br>    } <br>   <br>    public BaseDAO() <br>    { <br>    <br>    } <br><br>public DataSource getDataSource() { <br>return dataSource; <br>} <br><br>public void setDataSource(DataSource dataSource) { <br>this.dataSource = dataSource; <br>jt=new JdbcTemplate(dataSource,false); <br>} <br>   <br>} <br>实现的dao <br>public class CmsmailboxDao extends BaseDAO implements ICmsmailboxDao{ <br><br>public void createBean(final Cmsmailbox bean) throws DataAccessException{ <br>this.ht.save(bean); <br>} <br>public Cmsmailbox getBean(String ctid) throws DataAccessException { <br>return (Cmsmailbox) this.ht.get(Cmsmailbox.class, ctid); <br>} </p> <p> public Collection getBeans(final String cmbid,final String cmbtitle,final int offset, final int rowsToReturn, final String sort,<br>   final String order) throws DataAccessException {<br>  return (Collection) ht.execute(new HibernateCallback() {<br>   public Object doInHibernate(Session session)<br>     throws HibernateException {<br>    StringBuffer buf = new StringBuffer();<br>    buf.append("from com.xxx.Cmsmailbox bean ");</p> <p>    ......</p> <p>    Query query = session.createQuery(buf.toString());</p> <p>    ......</p> <p>    return query.list();</p> <p>   }</p> <p> });</p> <p>}<br>...... <br>} <br>配置文件 <br>&lt;bean id="dataSource" <br>class="org.apache.commons.dbcp.BasicDataSource"&gt; <br>&lt;property name="driverClassName"&gt; <br>&lt;value&gt;${SiteGroupDbDriver}&lt;/value&gt; <br>&lt;/property&gt; <br>&lt;property name="url"&gt; <br>&lt;value&gt;${SiteGroupDbUrl}&lt;/value&gt; <br>&lt;/property&gt; <br>&lt;property name="username"&gt; <br>&lt;value&gt;${SiteGroupDbUser}&lt;/value&gt; <br>&lt;/property&gt; <br>&lt;property name="password"&gt; <br>&lt;value&gt;${SiteGroupDbPassword}&lt;/value&gt; <br>&lt;/property&gt; <br>   &lt;property name="initialSize" value="5"/&gt; <br>   &lt;property name="maxActive" value="40" /&gt;   <br>       &lt;property name="maxIdle" value="30" /&gt;   <br>       &lt;property name="maxWait" value="10000" /&gt;   <br>       &lt;property name="defaultAutoCommit" value="true"/&gt;   <br>       &lt;property name="removeAbandoned" value="true"/&gt;   <br>       &lt;property name="removeAbandonedTimeout" value="30"/&gt;   <br>       &lt;property name="logAbandoned" value="true"/&gt; <br>       &lt;property name="validationQuery" value="SELECT count(*) FROM SSOAPP"/&gt; <br>   &lt;property name="testOnBorrow" value="true"/&gt; <br>&lt;/bean&gt; <br><br>&lt;bean id="baseDAO" class="com.xxx.dao.impl.BaseDAO" abstract="true"&gt; <br>&lt;property name="sessionFactory"&gt; <br>&lt;ref bean="sessionFactory" /&gt; <br>&lt;/property&gt; <br>&lt;property name="dataSource"&gt; <br>&lt;ref bean="dataSource" /&gt; <br>&lt;/property&gt; <br>&lt;/bean&gt; <br><br>&lt;bean name="/sysadmin/distributeCmsMailbox,/sysadmin/statisticCmsMailbox" <br>class="com.xxx.action.CmsMailboxAction"&gt; <br>&lt;property name="cmsMailboxService"&gt; <br>&lt;ref bean="cmsMailboxService" /&gt; <br>&lt;/property&gt; <br>&lt;property name="cmsdepartmentService"&gt; <br>&lt;ref bean="cmsdepartmentService" /&gt; <br>&lt;/property&gt; <br>&lt;property name="cmsdepartmenttypeService"&gt; <br>&lt;ref bean="cmsdepartmenttypeService"/&gt; <br>&lt;/property&gt; <br>&lt;/bean&gt; <br>&lt;bean id="cmsMailboxService" <br>class="com.xxx.service.impl.CmsMailboxService"&gt; <br>&lt;property name="cmsmailboxDao"&gt; <br>&lt;ref bean="cmsmailboxDao" /&gt; <br>&lt;/property&gt; <br>&lt;/bean&gt; <br>&lt;bean id="cmsmailboxDao" class="com.xxx.dao.impl.CmsmailboxDao" <br>parent="baseDAO"&gt; <br>&lt;/bean&gt; <br><br>以上是dao的一种典型配置 <br><br>下面是事务管理器的配置,实际上我的应用并未用到事务处理,只是出现上述错误后,怀疑 <br>是未加事务管理器的问题,结果加上后问题依旧 <br><br>        &lt;bean id="transactionManager" <br>class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; <br>                &lt;property name="sessionFactory"&gt;&lt;ref <br>bean="sessionFactory"/&gt;&lt;/property&gt; <br>        &lt;/bean&gt; <br>        &lt;bean id="transactionInterceptor" <br>class="org.springframework.transaction.interceptor.TransactionInterceptor"&gt; <br>                &lt;property name="transactionManager" ref="transactionManager"/&gt; <br>                &lt;property name="transactionAttributes"&gt; <br>                        &lt;props&gt; <br>                                &lt;prop key="*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; <br>                        &lt;/props&gt; <br>                &lt;/property&gt; <br>        &lt;/bean&gt; <br>        &lt;bean <br>class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"&gt; <br>                &lt;property name="beanNames"&gt; <br>                  &lt;value&gt;*Dao&lt;/value&gt; <br>                &lt;/property&gt; <br>                &lt;property name="interceptorNames"&gt; <br>                        &lt;list&gt; <br>                                &lt;value&gt;transactionInterceptor&lt;/value&gt; <br>                        &lt;/list&gt; <br>                &lt;/property&gt; <br>        &lt;/bean&gt; <br><br>目前已经可以排除的可能:1、数据库,在sqlserver下也会出现;2、jdbc驱动;3、hibernate及spring的版本;4、连接池,dbcp和c3p0都会出现 <br><br>感觉对于spring中使用hibernate的方式应该没有错误,应该是哪个地方的配置或是某个部分对整体架构产生了影响,希望大家都能来讨论下,给点思路</p> <p> </p><br/><strong>问题补充</strong><br/>现在已经是true了 <br />那个不设是所有的操作都不会写到数据库<br/><strong>问题补充</strong><br/>昨天用wvs测安全,居然把这个错误重现了,初步判断是和HibernateTemplate的并发有关
druid连接池获取连接超时异常
项目使用spring+springmvc+hibernate,数据库使用oracle11.2.0.1.0,允许的最大连接数为300,数据库服务器防火墙是关闭的。项目中有个定时任务(每天凌晨执行)使用jdbcTemplate同步数据。druid连接池异常信息如下: ``` [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-3] WARN com.alibaba.druid.pool.DruidDataSource - get connection timeout retry : 1 [2019-11-02 03:00:02.002] [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-3] ERROR org.quartz.core.JobRunShell - Job DEFAULT.syncSyldDataDetail threw an unhandled Exception: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:578) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at com.aqkk.task.SyncSyldData.start(SyncSyldData.java:33) ~[classes/:?] at com.aqkk.task.SyncSyldDataJob.executeInternal(SyncSyldDataJob.java:17) ~[classes/:?] at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:75) ~[spring-context-support-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.quartz.core.JobRunShell.run(JobRunShell.java:202) [quartz-2.3.0.jar:?] at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.3.0.jar:?] Caused by: com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at com.alibaba.druid.pool.DruidDataSource.getConnectionInternal(DruidDataSource.java:1512) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnectionDirect(DruidDataSource.java:1255) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:5007) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.filter.stat.StatFilter.dataSource_getConnection(StatFilter.java:680) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:5003) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1233) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:1225) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:90) ~[druid-1.1.10.jar:1.1.10] at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] ... 7 more [2019-11-02 03:00:02.002] [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-3] ERROR org.quartz.core.ErrorLogger - Job (DEFAULT.syncSyldDataDetail threw an exception. org.quartz.SchedulerException: Job threw an unhandled exception. at org.quartz.core.JobRunShell.run(JobRunShell.java:213) [quartz-2.3.0.jar:?] at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.3.0.jar:?] Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:578) ~[spring-jdbc-5.0.8.RELEASE.jar:5.0.8.RELEASE] at com.aqkk.task.SyncSyldData.start(SyncSyldData.java:33) ~[classes/:?] at com.aqkk.task.SyncSyldDataJob.executeInternal(SyncSyldDataJob.java:17) ~[classes/:?] at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:75) ~[spring-context-support-5.0.8.RELEASE.jar:5.0.8.RELEASE] at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.0.jar:?] ... 1 more Caused by: com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 1000, active 0, maxActive 350, creating 1 at com.alibaba.druid.pool.DruidDataSource.getConnectionInternal(DruidDataSource.java:1512) ~[druid-1.1.10.jar:1.1.10] at com.alibaba.druid.pool.DruidDataSource.getConnectionDirect(DruidDataSource.java:1255) ~[druid-1.1.10.jar:1.1.10] ``` druid配置信息如下: ``` <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${db.jdbcUrl}"/> <property name="username" value="${db.user}"/> <property name="password" value="${db.password}"/> <property name="driverClassName" value="${db.driver}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1"/> <property name="minIdle" value="20"/> <property name="maxActive" value="350"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="1000"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="10000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="30000"/> <property name="testWhileIdle" value="true"/> <property name="validationQuery" value="SELECT 1 FROM DUAL"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!-- 开启Druid的监控统计功能 --> <property name="filters" value="stat" /> </bean> ``` 为啥凌晨执行定时任务获取不到连接,9点上班系统又是正常运行的呢?
想用java写一个博客系统
想用java写一个自己的博客程序,现在问题来了,由于不想 用jsp+servlet感觉太乱,就苦苦在网上找该用什么框架,什么方案,能保证安全,能保证速度,这里问过一些朋友意见不一,下面是自己定出来的一些框架搭配 1、struts+spring+hibernate(感觉有hibernate的地方速度不怎么样) 2、springmvc+jdbctemplate 3、直接springmvc 4、springmvc+mybatis 这里想请教各位高手该如何选呢,或者有没有更好的搭配 我也只想满足安全与访问速度这点要求
Spring Mvc 整合jbpm 启动报错..
[quote]2012-10-30 11:34:23 org.apache.catalina.core.AprLifecycleListener init ��Ϣ: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;D:\Program Files\Apache Software Foundation\Tomcat 6.0\bin 2012-10-30 11:34:23 org.apache.coyote.http11.Http11Protocol init ��Ϣ: Initializing Coyote HTTP/1.1 on http-8080 2012-10-30 11:34:23 org.apache.catalina.startup.Catalina load ��Ϣ: Initialization processed in 1620 ms 2012-10-30 11:34:23 org.apache.catalina.core.StandardService start ��Ϣ: Starting service Catalina 2012-10-30 11:34:23 org.apache.catalina.core.StandardEngine start ��Ϣ: Starting Servlet Engine: Apache Tomcat/6.0.14 2012-10-30 11:34:25 org.apache.catalina.loader.WebappClassLoader validateJarFile ��Ϣ: validateJarFile(D:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\Spring\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class 2012-10-30 11:34:26 org.apache.catalina.core.ApplicationContext log ��Ϣ: Initializing Spring root WebApplicationContext log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader). log4j:WARN Please initialize the log4j system properly. 2012-10-30 11:34:30 org.apache.catalina.core.StandardContext listenerStart ����: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: [color=red]Error creating bean with name 'processEngine' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.jbpm.api.ProcessEngine org.jbpm.pvm.internal.processengine.SpringHelper.createProcessEngine()] threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/orm/hibernate3/LocalSessionFactoryBean at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:581) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:983) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:879) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:566) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)[/color] Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.jbpm.api.ProcessEngine org.jbpm.pvm.internal.processengine.SpringHelper.createProcessEngine()] threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/orm/hibernate3/LocalSessionFactoryBean at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:157) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:570) ... 38 more Caused by: java.lang.NoClassDefFoundError: org/springframework/orm/hibernate3/LocalSessionFactoryBean at org.jbpm.pvm.internal.cfg.ConfigurationImpl.buildProcessEngine(ConfigurationImpl.java:90) at org.jbpm.pvm.internal.processengine.SpringHelper.createProcessEngine(SpringHelper.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:145) ... 39 more Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.LocalSessionFactoryBean at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 46 more 2012-10-30 11:34:30 org.apache.catalina.core.StandardContext start ����: Error listenerStart 2012-10-30 11:34:30 org.apache.catalina.core.StandardContext start ����: Context [/Spring] startup failed due to previous errors 2012-10-30 11:34:30 org.apache.catalina.core.ApplicationContext log ��Ϣ: Closing Spring root WebApplicationContext 2012-10-30 11:34:30 org.jbpm.internal.log.Jdk14Log info ��Ϣ: loading schema resource: jpdl-4.0.xsd 2012-10-30 11:34:30 org.jbpm.internal.log.Jdk14Log info ��Ϣ: loading schema resource: jpdl-4.2.xsd 2012-10-30 11:34:30 org.jbpm.internal.log.Jdk14Log info ��Ϣ: loading schema resource: jpdl-4.3.xsd 2012-10-30 11:34:30 org.jbpm.internal.log.Jdk14Log info ��Ϣ: loading schema resource: jpdl-4.4.xsd 2012-10-30 11:34:31 org.apache.coyote.http11.Http11Protocol start ��Ϣ: Starting Coyote HTTP/1.1 on http-8080 2012-10-30 11:34:31 org.apache.jk.common.ChannelSocket init ��Ϣ: JK: ajp13 listening on /0.0.0.0:8009 2012-10-30 11:34:31 org.apache.jk.server.JkMain start ��Ϣ: Jk running ID=0 time=0/30 config=null 2012-10-30 11:34:31 org.apache.catalina.startup.Catalina start ��Ϣ: Server startup in 7646 ms [/quote] applicationContext.xml配置文件 [quote]<?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:p="http://www.springframework.org/schema/p" 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/context http://www.springframework.org/schema/context/spring-context-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="springHelper" class="org.jbpm.pvm.internal.processengine.SpringHelper" /> <bean id="processEngine" factory-bean="springHelper" factory-method="createProcessEngine" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:jbpm.hibernate.cfg.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 --> <context:component-scan base-package="com.dao"/> <context:component-scan base-package="com.service"/> <!-- 配置数据源--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/sampledb" p:username="root" p:password="root" /> <!-- 配置Jdbc模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" /> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 --> <aop:config proxy-target-class="true"> <aop:pointcut id="serviceMethod" expression=" execution(* com.service..*(..))" /> <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> </beans> [/quote] 我也在网上找了一下资料,有的说jar包冲突, 我试了删除jar包, 还是报错, 求解决啊, 谢谢了!
关于spring事务管理
先简单看看相关配置: <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="dataSource" /> </bean> …… <tx:annotation-driven transaction-manager="transactionManager" /> 不是我配的。我想问的是 1,里面有用于hibernate事务的HibernateTransactionManager和用于jdbc事务的DataSourceTransactionManager两个事务管理bean。可以多于一个吗? 2,如果可以。在配置中我没有发现dataSourceTransactionManager被任何地方用到过。他是不是在用到jdbcTemplate时spring会自己寻找dataSourceTransactionManager? 补充,现在是没有dataSourceTransactionManager这个bean时若使用oracle会游标只增不减。 [b]问题补充:[/b] 好像无法把分分给多个人。
子类获取父类的属性为什么会是空.(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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean--> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/datasource/jdbc.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClassName}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </bean> <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="dataSource"/> </bean> <bean id="abstractSupperDao" class="com.huawei.bus.dao.AbstractSupperDao"> <property name="jdbctemplate" ref="jdbctemplate"/> </bean> </beans> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="queryAction" class="com.huawei.bus.struts2.QuerySubscriber" scope="prototype"> <property name="aisBusBIZ" ref="aisBusBIZ"/> </bean> <bean id="aisBusBIZ" class="com.huawei.bus.biz.impl.AisBusBizImpl"> <property name="aisBusDAO" ref="aisBusDAO"/> </bean> <bean id="aisBusDAO" class="com.huawei.bus.dao.impl.AisBusDAOImpl"/> <bean id="getSqlValue" class="com.huawei.bus.util.GetSqlValue"> <property name="map"> <map> <entry key="query_subscriber" value="SELECT SUBSCRIBERKEY,APPLYTIME,EXPIRETIME FROM CBE_SUBSCRIBER"/> </map> </property> </bean> </beans> ---------AbstractSupperDao.java文件 public class AbstractSupperDao { public JdbcTemplate jdbctemplate; public JdbcTemplate getJdbctemplate() { return jdbctemplate; } public void setJdbctemplate(JdbcTemplate jdbctemplate) { this.jdbctemplate = jdbctemplate; } } --------AisBusDAOImpl.java文件 public class AisBusDAOImpl extends AbstractSupperDao implements IAisBusDAO { @SuppressWarnings("unchecked") public List<Subscriber> querySubscriber() { GetSqlValue getSqlValue = (GetSqlValue)PubUtilServiceLocator.getInstance().getService("getSqlValue"); String sql = getSqlValue.getMap().get(SqlKeyUtils.QUERY_SUBSCRIBER); List list = this.jdbctemplate.queryForList(sql); for(Object obj : list){ Map<String,String> map = (Map)obj; Integer sbuscriberkey = Integer.valueOf(String.valueOf((map.get("sbuscriberkey")))); String applytime = String.valueOf(map.get("applytime")); String expiretime = String.valueOf(map.get("expiretime")); System.out.println("用户键值:" + sbuscriberkey + ";应用时间:" + applytime + ";有限期:" + expiretime); } return list; } }
配置hibernate4多租客错误
配置hibernate4多租客 错误,不加多租客配置则正确。 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: HHH000152: JDBC URL was not specified by property hibernate.connection.url at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4334) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138) 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:jee="http://www.springframework.org/schema/jee" 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/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/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"> <context:component-scan base-package=">com.buddha"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="jdbcUrl"> <value>jdbc:oracle:thin:@localhost:1521:myoracle</value> </property> <property name="user"> <value>shulizhi</value> </property> <property name="password"> <value>shulizhi</value> </property> <!-- 连接池中保留的最小连接数。--> <property name="minPoolSize"> <value>5</value> </property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize"> <value>50</value> </property> <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize"> <value>5</value> </property> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime"> <value>30</value> </property> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement"> <value>5</value> </property> <!-- JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 <property name="maxStatements"> <value>0</value> </property> --> <property name="maxStatements"> <value>0</value> </property> <property name="maxStatementsPerConnection"> <value>100</value> </property> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod"> <value>60</value> </property> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts"> <value>30</value> </property> <!-- 获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false --> <property name="breakAfterAcquireFailure"> <value>false</value> </property> <!-- 因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 等方法来提升连接测试的性能。Default: false <property name="testConnectionOnCheckout"> <value>false</value> </property> --> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.connection.release_mode">auto</prop> <prop key="hibernate.autoReconnect">true</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="hibernate.current_session_context_class"> org.springframework.orm.hibernate4.SpringSessionContext </prop> <prop key="hibernate.multiTenancy">SCHEMA</prop> <prop key="hibernate.tenant_identifier_resolver">com.buddha.domain.hibernate.TenantIdResolver</prop> <prop key="hibernate.multi_tenant_connection_provider">com.buddha.domain.hibernate.SchemaBasedMultiTenantConnectionProvider</prop> </props> </property> <property name="mappingDirectoryLocations"> <list> <value>classpath:com/buddha/domain/</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <context:annotation-config /> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> </beans>
请问使用JdbcTemplate新增数据如何获得改数据的自增id?
请问使用JdbcTemplate做insert操作的时候。该表的主键为自增。我需要改条数据的id作为外键进行其他操作。用update的方法好像不能返回插入的对象。请问如何获得改id。 ps:请别说hibernate与ibatis。
org.springframework.beans.factory.BeanCreationException 异常
``` HTTP Status 500 - Servlet.init() for servlet viewspace threw exception type Exception report message Servlet.init() for servlet viewspace threw exception description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: Servlet.init() for servlet viewspace threw exception org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Unknown Source) root cause org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/viewspace-servlet.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Unknown Source) root cause org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:702) org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1180) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351) org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Unknown Source) note The full stack trace of the root cause is available in the Apache Tomcat/9.0.0.M17 logs. ``` ``` 这是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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 自动扫描组件 --> <context:component-scan base-package="org.alex.samples"/> <!-- 打开注解驱动 --> <mvc:annotation-driven/> <!-- 配置jsp视图解析器 ,需要有jstl这个jar包,否则不能映射--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/view/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 国际化 --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames" value="i18n.message"></property> <property name="useCodeAsDefaultMessage" value="true" /> <property name="defaultEncoding" value="UTF-8"/> </bean> <!-- 基于Session的国际化配置--> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> <!-- 动态语言切换 --> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="locale"></property> </bean> <!-- 静态资源访问 --> <mvc:resources location="/static/lib/" mapping="/static/lib/**" /> <mvc:resources location="/static/assets/" mapping="/static/assets/**" /> <mvc:resources location="/static/docs/" mapping="/static/docs/**" /> <!-- JSR 303 Validator --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property> <property name="validationMessageSource" ref="messageSource"/> </bean> <!-- 数据库配置连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- MySQL数据库配置--> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean> <!-- hibernate --> <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="org.alex.samples"/> <property name="hibernateProperties"> <props> <prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="show_sql">true</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false" /> <!-- 配置jdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" abstract="false" lazy-init="false" autowire="default"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <bean id="UserDAOImpl" class="org.alex.samples.dao.UserDAOImpl"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate" /> </property> </bean> <bean id="SubDAOImpl" class="org.alex.samples.dao.SubDAOImpl"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate" /> </property> </bean> </beans> ```
求大神,求大神,求大神,求大神,spring配置多租户错误,去掉多租户配置不报错。
7-23 13:04:58,761 ERROR DriverManagerConnectionProviderImpl - HHH000152: JDBC URL was not specified by property hibernate.connection.url 07-23 13:04:58,801 ERROR ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/spring/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: HHH000152: JDBC URL was not specified by property hibernate.connection.url at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:684) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827) --------------------文件配置去掉多租户配置不报错 <?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:jee="http://www.springframework.org/schema/jee" 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/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/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"> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="jdbcUrl"> <value>jdbc:oracle:thin:@localhost:1521:myoracle</value> </property> <property name="user"> <value>shulizhi</value> </property> <property name="password"> <value>shulizhi</value> </property> <!-- 连接池中保留的最小连接数。--> <property name="minPoolSize"> <value>5</value> </property> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize"> <value>50</value> </property> <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize"> <value>5</value> </property> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime"> <value>30</value> </property> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement"> <value>5</value> </property> <!-- JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 <property name="maxStatements"> <value>0</value> </property> --> <property name="maxStatements"> <value>0</value> </property> <property name="maxStatementsPerConnection"> <value>100</value> </property> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod"> <value>60</value> </property> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts"> <value>30</value> </property> <!-- 获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false --> <property name="breakAfterAcquireFailure"> <value>false</value> </property> <!-- 因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 等方法来提升连接测试的性能。Default: false <property name="testConnectionOnCheckout"> <value>false</value> </property> --> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.connection.release_mode">auto</prop> <prop key="hibernate.autoReconnect">true</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="hibernate.multiTenancy">SCHEMA</prop> <prop key="hibernate.tenant_identifier_resolver">hotel.dao.hibernate.TenantIdResolver</prop> <prop key="hibernate.multi_tenant_connection_provider">hotel.dao.hibernate.SchemaBasedMultiTenantConnectionProvider</prop> </props> </property> <property name="mappingDirectoryLocations"> <list> <value>classpath:com/buddha/domain/</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <context:annotation-config /> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> </beans>
请教:spring配置mysql/access多数据源的动态切换问题,急用,十分感谢!
请教:spring配置mysql/access多数据源在切换到access数据源时抛No Session found for current thread错误是怎么回事?请大侠详加指导,十分感谢,急用!我的配置文件如下: <?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:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" 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 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd" default-autowire="byName" default-lazy-init="false"> <!-- 自动扫描dao和service包(自动注入) --> <context:component-scan base-package="org.framework.core.common.dao.*" /> <context:component-scan base-package="org.framework.core.common.service.*" /> <!-- 加载service,此时要排除要controller,因为controller已经spring-mvc中加载过了 --> <context:component-scan base-package="test.*,framework.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:dbconfig.properties" /> <!-- 配置数据源1 --> <bean name="mysqlDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url.mysql}" /> <property name="username" value="${jdbc.username.jeecg}" /> <property name="password" value="${jdbc.password.jeecg}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery.sqlserver}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> </bean> <!-- 数据源2 : access数据源 --> <bean id="accessDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="sun.jdbc.odbc.JdbcOdbcDriver" /> <property name="url" value="jdbc:odbc:users" /> <property name="username" value="" /> <property name="password" value="" /> </bean> <!-- access sessionFactory --> <bean id="aceessSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="accessDataSource" /> <property name="hibernateProperties"> <props> <!-- access 语法和MSSQL相似 所以用的MSSQL方言,或者可以使用第三方方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="hibernate.jdbc.fetch_size">50</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- 数据源集合 --> <bean id="dataSource" class="org.jeecgframework.core.extend.datasource.DynamicDataSource"> <property name="targetDataSources"> <map key-type="org.jeecgframework.core.extend.datasource.DataSourceType"> <entry key="mysqlDataSource" value-ref="mysqlDataSource" /> </map> </property> <property name="defaultTargetDataSource" ref="mysqlDataSource" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="entityInterceptor" ref="hiberAspect"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop> </props> </property> <!-- 注解方式配置 --> <property name="packagesToScan"> <list> <value>system.pojo.*</value> <value>demo.entity.*</value> <value>test.entity.*</value> <value>test.bussiness.db.UserInfo</value> </list> </property> </bean> <bean id="accessJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="accessDataSource"/> </property> </bean> <bean id="accessTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="aceessSessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="accessTransactionManager"> <tx:attributes> <tx:method name="exists" read-only="true" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cors.bussiness.db..*.*(..))" /> </aop:config> <!-- JDBC配置 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <!-- JDBC配置 --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource" /> </bean> <!-- 配置事物管理器,在*ServiceImpl里写@Transactional就可以启用事物管理 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
jdbctemplate是不是应该置为prototype呢?
我觉得应该把jdbctemplate设为多例的,因为dataSource是线程安全的(同步的). <br />在项目只有一个数据源(dataSource),可以有多个连接(jdbctemplate). <br />这样才能保证数据的安全性. <br /> <br />&lt;?xml version="1.0" encoding="UTF-8"?&gt; <br />&lt;beans <br /> xmlns="http://www.springframework.org/schema/beans" <br /> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <br /> xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"&gt; <br /> &lt;!-- bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; <br /> &lt;property name="configLocation"&gt; <br /> &lt;value&gt;classpath:hibernate.cfg.xml&lt;/value&gt; <br /> &lt;/property&gt; <br /> &lt;/bean--&gt; <br /> <br /> &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; <br /> &lt;property name="locations"&gt; <br /> &lt;list&gt; <br /> &lt;value&gt;classpath:/datasource/jdbc.properties&lt;/value&gt; <br /> &lt;/list&gt; <br /> &lt;/property&gt; <br /> &lt;/bean&gt; <br /> <br /> &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; <br /> &lt;property name="driverClassName" value="${driverClassName}"/&gt; <br /> &lt;property name="url" value="${url}"/&gt; <br /> &lt;property name="username" value="${username}"/&gt; <br /> &lt;property name="password" value="${password}"/&gt; <br /> &lt;/bean&gt; <br /> <br /> &lt;bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate" scope="prototype"&gt; <br /> &lt;constructor-arg ref="dataSource"/&gt; <br /> &lt;/bean&gt; <br /> <br /> &lt;bean id="abstractSupperDao" class="com.huawei.bus.dao.AbstractSupperDao" scope="singleton"&gt; <br /> &lt;property name="jdbctemplate" ref="jdbctemplate"/&gt; <br /> &lt;/bean&gt; <br />&lt;/beans&gt;
菜鸟:高手帮看一下什么 原因?用代理方式时jdbcTemplate为NULL
<p>用代理方式执行时jdbcTemplate为NULL,高手帮看一下怎么回事呀????</p> <p> </p> <p>Exception in thread "main" java.lang.reflect.InvocationTargetException<br> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br> at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)<br> at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)<br> at java.lang.reflect.Method.invoke(Method.java:597)<br> at com.okgj.core.MessageExecutor.invoke(MessageExecutor.java:46)<br> at com.okgj.core.MessageExecutor.main(MessageExecutor.java:64)<br>Caused by: java.lang.NullPointerException<br> at com.okgj.service.dao.impl.UserDaoImpl.getUserInfo(UserDaoImpl.java:42)<br> at com.okgj.service.impl.UserServiceImpl.getUserInfo(UserServiceImpl.java:43)<br> at com.okgj.service.impl.UserServiceImpl$$EnhancerByCGLIB$$398c34af.getUserInfo(&lt;generated&gt;)<br> ... 6 more</p> <p> </p> <p>package com.okgj.service.dao.impl;<br><br>import java.util.ArrayList;<br>import java.util.List;<br><br>import javax.annotation.Resource;<br><br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.jdbc.core.JdbcTemplate;<br>import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;<br>import org.springframework.jdbc.core.support.JdbcDaoSupport;<br>import org.springframework.orm.hibernate3.HibernateTemplate;<br>import org.springframework.stereotype.Repository;<br><br>import com.okgj.service.dao.UserDao;<br>import com.okgj.service.entity.userInfo;<br><br>@Repository<br>public class UserDaoImpl implements UserDao {<br><br>    private JdbcTemplate jdbcTemplate;<br><br>    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {<br>        this.jdbcTemplate = jdbcTemplate;<br>    }<br><br>    public JdbcTemplate getJdbcTemplate() {<br>        return jdbcTemplate;<br>    }<br><br>    @Override<br>    public List getUserInfo(String condition) {<br>        String sql = "select username,userpwd from tb_user";<br>        List userList = jdbcTemplate.queryForList(sql);<br>        return userList;<br>    }<br>}</p> <p> </p> <p>debug下面类时不会出错,</p> <p> </p> <p>package com.okgj.service.impl;<br><br>import java.lang.reflect.Method;<br>import java.util.List;<br><br>import javax.annotation.Resource;<br><br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.support.FileSystemXmlApplicationContext;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br><br>import com.okgj.service.UserService;<br>import com.okgj.service.dao.UserDao;<br>import com.okgj.service.dao.impl.UserDaoImpl;<br><br>import org.springframework.transaction.annotation.Propagation;<br><br>@Service<br>@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)<br>public class UserServiceImpl implements UserService {<br>    @Resource<br>    private UserDao userDao = new UserDaoImpl();<br><br>    public UserDao getUserDao() {<br>        return userDao;<br>    }<br><br>    public void setUserDao(UserDao userDao) {<br>        this.userDao = userDao;<br>    }<br><br>    public List getUserInfo(String condition) {<br>        return userDao.getUserInfo(condition);<br>    }<br><br>    public static void main(String[] args) throws Throwable {<br>        ApplicationContext context = new FileSystemXmlApplicationContext(<br>                "classpath:spring-service.xml");<br>         UserService userService = (UserService)<br>         context.getBean("userService");<br>        <br>         List list = userService.getUserInfo("");<br>         System.out.println(list.toString());<br><br>    }<br><br>}</p> <p> </p> <p>而通过代理的方式执行却报上面的错,为什么 呀?急呀!!!!!!</p> <p> </p> <p>package com.okgj.service.impl;<br><br>import java.lang.reflect.Method;<br>import java.util.List;<br><br>import javax.annotation.Resource;<br><br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.support.FileSystemXmlApplicationContext;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br><br>import com.okgj.service.UserService;<br>import com.okgj.service.dao.UserDao;<br>import com.okgj.service.dao.impl.UserDaoImpl;<br><br>import org.springframework.transaction.annotation.Propagation;<br><br>@Service<br>@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)<br>public class UserServiceImpl implements UserService {<br>    @Resource<br>    private UserDao userDao = new UserDaoImpl();<br><br>    public UserDao getUserDao() {<br>        return userDao;<br>    }<br><br>    public void setUserDao(UserDao userDao) {<br>        this.userDao = userDao;<br>    }<br><br>    public List getUserInfo(String condition) {<br>        return userDao.getUserInfo(condition);<br>    }<br><br>    public static void main(String[] args) throws Throwable {<br>        ApplicationContext context = new FileSystemXmlApplicationContext(<br>                "classpath:spring-service.xml");<br>        <br><br>        Class&lt;?&gt; c = (Class&lt;?&gt;) context.getBean("userService").getClass();<br>        Object obj = c.newInstance();<br><br>        Method m = c.getMethod("getUserInfo",<br>                new Class[] { java.lang.String.class });<br>        Object result = m.invoke(obj, new Object[] { "" });<br>    }<br><br>}</p> <p> </p> <p>spring的配置文件如下:</p> <p>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br><br>&lt;beans xmlns="http://www.springframework.org/schema/beans"<br>    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"<br>    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"<br>    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd<br>                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd<br>                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd<br>                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"&gt;<br><br>    &lt;import resource="spring-db-connectionpool.xml" /&gt;<br><br>    &lt;bean id="userService" class="com.okgj.service.impl.UserServiceImpl"&gt;<br>        &lt;property name="userDao" ref="userDao" /&gt;<br>    &lt;/bean&gt;<br>    &lt;bean id="orderService" class="com.okgj.service.impl.OrderServiceImpl"&gt;<br>        &lt;property name="userDao" ref="userDao" /&gt;<br>    &lt;/bean&gt;<br>    &lt;bean id="userDao" class="com.okgj.service.dao.impl.UserDaoImpl"&gt;<br>        &lt;property name="jdbcTemplate" ref="jdbcTemplate" /&gt;<br>    &lt;/bean&gt;<br><br>&lt;/beans&gt;</p> <p> </p> <p>&lt;!--数据源配置,使用应用内的C3P0数据库连接池  --&gt;<br>    &lt;bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"<br>        destroy-method="close"&gt;<br>        &lt;property name="driverClass" value="com.mysql.jdbc.Driver" /&gt;<br>        &lt;property name="jdbcUrl" value="jdbc:mysql://localhost/projectmanagesystem" /&gt;<br>        &lt;property name="user" value="root" /&gt;<br>        &lt;property name="password" value="" /&gt;<br>        &lt;property name="numHelperThreads" value="5" /&gt;<br>        &lt;property name="maxPoolSize" value="20" /&gt;<br>        &lt;property name="minPoolSize" value="5" /&gt;<br>        &lt;property name="initialPoolSize" value="5" /&gt;<br>    &lt;/bean&gt;</p> <p> </p> <p>&lt;!-- 添加AnnotationSessionFactoryBean,提供注解注入支持 --&gt;<br>    &lt;bean id="sessionFactory"<br>        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;<br>        &lt;property name="dataSource" ref="dataSource" /&gt;<br>        &lt;property name="packagesToScan"&gt;<br>            &lt;list&gt;<br>                &lt;value&gt;com.okgj.service.*&lt;/value&gt;<br>            &lt;/list&gt;<br>        &lt;/property&gt;<br>        &lt;property name="hibernateProperties"&gt;<br>            &lt;props&gt;<br>                &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;<br>                &lt;prop key="hibernate.show_sql"&gt;false&lt;/prop&gt;<br>                &lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt;<br>                &lt;prop key="hibernate.format_sql"&gt;false&lt;/prop&gt;<br>                &lt;!-- &lt;prop key="hibernate.connection.autocommit"&gt;true &lt;/prop&gt;--&gt;<br>                &lt;prop key="hibernate.cache.provider_class"&gt;<br>                    net.sf.ehcache.hibernate.EhCacheProvider<br>                &lt;/prop&gt;<br>                &lt;prop key="hibernate.cache.use_query_cache"&gt;true&lt;/prop&gt;<br>            &lt;/props&gt;<br>        &lt;/property&gt;<br>    &lt;/bean&gt;<br><br>    &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&gt;<br>        &lt;property name="sessionFactory" ref="sessionFactory" /&gt;<br>    &lt;/bean&gt;<br><br>    &lt;!--   JdbcTemplate   --&gt;<br>    &lt;bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"&gt;<br>        &lt;property name="dataSource" ref="dataSource" /&gt;<br>    &lt;/bean&gt;</p> <p> </p>
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
相关热词 c# 图片上传 c# gdi 占用内存 c#中遍历字典 c#控制台模拟dos c# 斜率 最小二乘法 c#进程延迟 c# mysql完整项目 c# grid 总行数 c# web浏览器插件 c# xml 生成xsd
立即提问