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问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring3+hibernate4中使用spring管理事务,事务不自动提交问题

<div class="iteye-blog-content-contain" style="font-size: 14px;"> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd "&gt; &lt;context:property-placeholder location="classpath:hibernate.properties" /&gt; &lt;context:annotation-config&gt;&lt;/context:annotation-config&gt; &lt;context:component-scan base-package="com.*"&gt; &lt;context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /&gt; &lt;/context:component-scan&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="driverClassName" value="${hibernate.driverClassName}"&gt;&lt;/property&gt; &lt;property name="url" value="${hibernate.url}"&gt;&lt;/property&gt; &lt;property name="username" value="${hibernate.name}"&gt;&lt;/property&gt; &lt;property name="password" value="${hibernate.password}"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.OracleDialect &lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt; &lt;prop key="hibernate.current_session_context_class"&gt;org.springframework.orm.hibernate4.SpringSessionContext&lt;/prop&gt; &lt;prop key="hibernate.query.factory_class"&gt;org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory&lt;/prop&gt; &lt;prop key="hibernate.jdbc.fetch_size"&gt;50&lt;/prop&gt; &lt;prop key="hibernate.jdbc.batch_size"&gt;25&lt;/prop&gt; &lt;prop key="hibernate.temp.use_jdbc_metadata_defaults"&gt;false&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt; com/entity/User.hbm.xml &lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;!-- 开启AOP监听 只对当前配置文件有效 --&gt; &lt;aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true"/&gt; &lt;!-- 开启注解事务 只对当前配置文件有效 --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" mode="aspectj" proxy-target-class="true"/&gt; &lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt; &lt;tx:attributes&gt; &lt;tx:method name="get*" propagation="REQUIRED"/&gt; &lt;tx:method name="delete*" propagation="REQUIRED"/&gt; &lt;tx:method name="update*" propagation="REQUIRED" /&gt; &lt;tx:method name="add*" propagation="REQUIRED" /&gt; &lt;tx:method name="*" propagation="REQUIRED"&gt;&lt;/tx:method&gt; &lt;/tx:attributes&gt; &lt;/tx:advice&gt; &lt;aop:config expose-proxy="true" proxy-target-class="true"&gt; &lt;aop:pointcut expression="within(com.*)" id="allMethod" /&gt; &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="allMethod" /&gt; &lt;/aop:config&gt; &lt;/beans&gt;</pre> <pre name="code" class="java">package com.test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.dao.UserDao; import com.entity.User; @ContextConfiguration({"classpath:applicationContext.xml"}) @Transactional @RunWith(SpringJUnit4ClassRunner.class) public class Test { @Autowired private UserDao userDao; @org.junit.Test public void test() { User user=new User(); user.setEMail("993126013@qq.com"); user.setRealname("张三"); user.setPassword("12333333"); user.setMobile("15850597175"); user.setSex("1"); user.setUsername("zhulljk"); int i=userDao.addUser(user); System.out.println(userDao.getUsername(user.getUsername()).getId()); } }</pre> <pre name="code" class="java">Hibernate: select MYSEQ.nextval from dual org.hibernate.internal.SessionFactoryImpl@1de8adb Hibernate: insert into ZHUT.S_USER (USERNAME, REALNAME, PASSWORD, SEX, TELPHONE, MOBILE, E_MAIL, ID) values (?, ?, ?, ?, ?, ?, ?, ?) Hibernate: select this_.ID as ID0_0_, this_.USERNAME as USERNAME0_0_, this_.REALNAME as REALNAME0_0_, this_.PASSWORD as PASSWORD0_0_, this_.SEX as SEX0_0_, this_.TELPHONE as TELPHONE0_0_, this_.MOBILE as MOBILE0_0_, this_.E_MAIL as E8_0_0_ from ZHUT.S_USER this_ where this_.USERNAME=? 41</pre> <pre name="code" class="java">sql已经执行成功,但是事务没有提交,我使用spring来管理事务,不知道哪个地方出现错误,求解惑。。</pre> <p> </p> <p> </p> </div>

spring + hibernate 动态切换数据源

项目用的是struts2 + spring + hibernate,项目的查询基本上用的都是SQL原生查询, 获取连接的方式是用hibernate的session.connection();(如下图所示),现在需要动态 切换数据源,要如何才能改变数据源呢? ![图片说明](https://img-ask.csdn.net/upload/201701/18/1484706178_817129.png)

kotlin语言的Spring整合hibernate注入一个dao类 时报错

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is kotlin.UninitializedPropertyAccessException: lateinit property releaseStatusRepository has not been in :Caused by: kotlin.UninitializedPropertyAccessException: lateinit property XXXRepository has not been initializeditialized

spring jdbcTemplate怎么得到新插入数据的主键(varchar2类型)

在网上看到用KeyHelper 可以得到数字类型的主键,但是表的主键guid是varchar类型的,用Spring的jdbcTemplate有什么方法可以得到新插入数据的主键? 用的是Hibernate 数据库是Oracle 求大神帮忙了啊! 不用先插入了,再查询的方法怎么破?

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的并发有关

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 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; } } 请大师指导下 谢啦!

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); } } 请教各位大神

请问使用JdbcTemplate新增数据如何获得改数据的自增id?

请问使用JdbcTemplate做insert操作的时候。该表的主键为自增。我需要改条数据的id作为外键进行其他操作。用update的方法好像不能返回插入的对象。请问如何获得改id。 ps:请别说hibernate与ibatis。

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没注入成功,这是为啥啊? 谢谢

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配置多数据源动态切换,java实体如何和各个数据库实例映射?

我的一个javaweb项目,需要用到多个数据源,都是oracle实例,我用spring配置了数据源的动态切换。使用AOP在service层做拦截,然后用注解DataSource来标示所要选择的数据源。现在我有一个问题,就是我用数据库操作时,hibernate是面向对象的,我该如何将不同的java实体映射到不同的数据源上(不同数据库表结构不同)。比如一个product包中的java实体映射到数据库1,cart包中的实体映射到数据库2。如何做到呢?

springmvc+hibernate整合事务不回滚,求解

最近心血来潮研究下了springmvc,发现比struts2好用多了,配置也方便,捣鼓了一阵,最后想把hibernate也整进去,结果悲剧就来了,事务就是不回滚,实在没招了,哪位大侠给看下,上代码 springmvc-servlet.xml [code="java"]<mvc:annotation-driven/> <!-- 扫描注解时,将service,DAO层的注解排除,只扫描Controller注解 --> <context:component-scan base-package="com.springmvc" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="html" value="text/html" /> <entry key="json" value="application/json" /> </map> </property> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> </list> </property> </bean>[/code]applicationContext-db.xml [code="java"]<context:annotation-config /> <context:component-scan base-package="com.springmvc" /> <!-- 配置数据源 --> <bean id = "mappings" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="classpath:dataSources.properties"></property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <property name="maxActive" value="${maxActive}" /> <property name="maxIdle" value="${maxIdle}" /> <property name="maxWait" value="${maxWait}" /> <property name="defaultAutoCommit" value="${defaultAutoCommit}" /> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 扫描的domain包路径 --> <property name="packagesToScan" value="com.springmvc.domain"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">none</prop> <prop key="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider</prop> <prop key="hibernate.search.default.transaction.merge_factor">100</prop> <prop key="hibernate.search.default.transaction.max_buffered_docs">100</prop> <prop key="hibernate.search.autoregister_listeners">true</prop> <prop key="hibernate.search.indexing_strategy">manual</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>[/code]applicationContext-aop.xml[code="java"]<tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="create*" propagation="REQUIRED"/> <tx:method name="do*" propagation="REQUIRED"/> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="remove*" propagation="REQUIRED"/> <tx:method name="get*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="*"/> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <aop:pointcut expression="execution(public * com.springmvc.service.impl.*ServiceImpl.*(..))" id="allServiceMethod"/> <aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" /> </aop:config>[/code]UserServiceImpl[code="java"]Service(value = "userService") @Transactional(rollbackFor=Exception.class) public class UserServiceImpl implements UserService { @Autowired private UserDAO userDAO; @Override public void addUser(User user) { userDAO.addUser(user); } }[/code]UserDAOImpl [code="java"]@Repository(value = "userDAO") public class UserDAOImpl extends HibernateDaoSupport implements UserDAO { private Logger logger = Logger.getLogger(getClass()); @Override public void addUser(User user) { logger.debug("新增用户"); this.getHibernateTemplate().save(user); }[/code]UserServiceTest[code="java"]@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"file:webroot/WEB-INF/springmvc-servlet.xml","classpath:applicationContext-*.xml"}) public class UserServiceTest{ @Autowired private UserService userService; @Test public void testAddUser() { User user1 = new User(); user1.setCode("A002"); user1.setName("haha"); userService.addUser(user1); User user2 = new User(); user2.setCode("A001"); user2.setName("haha"); userService.addUser(user2); User user3 = new User(); user3.setCode("A001");//code是唯一的,这里报唯一约束错误,前面两条数据是不是应该插入失败? user3.setName("haha"); userService.addUser(user3); } }[/code]

Spring jdbc getJdbcTemplate() queryForObject如何返回对象

这是我的代码 希望您花几分钟不到的时间帮我看一下 我搞了1天了 楞是不明白一运行就报 异常捕获在持久层:Incorrect column count: expected 1, actual 3这个错误 结果网上搜不到这个异常是个什么 public User IsQueryOne(String id) throws Exception { try{ User user = (User) this.getJdbcTemplate().queryForObject("select * from test where id="+id,User.class); return user; }catch(Exception e){ System.out.println("异常捕获在持久层:"+e.getMessage()); } return null; } 网上有很多介绍SPRING MVC的例子 但是多半几乎是一个例子占了谷歌的前2页。。在往后搜就是IBATIS了 所以请高手给看一下 那个User.class是一个POJO类 我希望查询完毕后可以返回一个user对象 毕竟我这个是按ID查的 就一条记录 就是不明白为什么会错 [b]问题补充:[/b] 知道是怎么回事了 这个方法看起来以为和HIBERNATE的一样 结果是完全不同 需要写一个类 public class UserRowMapper implements RowMapper { public Object mapRow(ResultSet rs, int value) throws SQLException { User user = new User(); user.setId(new Integer(rs.getInt("id"))); user.setUsername(rs.getString("username")); user.setAge(rs.getString("age")); return user; } } 然后在我的方法里直接返回 public User IsQueryOne(String id) throws RuntimeException { String sql="select * from test where id="+id; //现在你看到了我们写的UserRowMapper这个类是多么的方便 return (User) this.getJdbcTemplate().queryForObject(sql,new UserRowMapper()); } 刚玩这个 下来搞搞AOP了。。。不然acegi搞起来有难度....哎~~无聊呃。。。。

spring boot jpa 动态参数传表名,执行时自动添加单引号?

想通过sql语句自动创建表的列名但是传过来的两个参数值会自动添加了单引号,导致sq执行不成功。请问该怎么解决。 ``` @Modifying @Query(value="alter table ?1 add ?2 varchar(255) default ''",nativeQuery = true) void addTbcouponItemColumn(String table_name,String column_name); ```

Spring如何从mysql数据库中读取数据(json格式)并传给前台

菜鸟提问大神: 譬如数据库中有个用户表user,字段有id,name,age sping(controller、service等层)该怎么写才能获取用户表里的数据 然后,又怎么将这些传给前台 请贴出详细的示例代码,谢谢~

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点上班系统又是正常运行的呢?

jdbc和mybatis或者hibernate这种框架的效率能差多少?

jdbc和mybatis或者hibernate这种框架的效率能差多少? jdbc和mybatis或者hibernate这种框架的效率能差多少? jdbc和mybatis或者hibernate这种框架的效率能差多少?

子类获取父类的属性为什么会是空.(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; } }

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

再不跳槽,应届毕业生拿的都比我多了!

跳槽几乎是每个人职业生涯的一部分,很多HR说“三年两跳”已经是一个跳槽频繁与否的阈值了,可为什么市面上有很多程序员不到一年就跳槽呢?他们不担心影响履历吗? PayScale之前发布的**《员工最短任期公司排行榜》中,两家码农大厂Amazon和Google**,以1年和1.1年的员工任期中位数分列第二、第四名。 PayScale:员工最短任期公司排行榜 意外的是,任期中位数极小的这两家公司,薪资...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

数据库——玩转SQL语句(以MySQL为例)

一、前言 照着大学的SQL server来学

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

华为初面+综合面试(Java技术面)附上面试题

华为面试整体流程大致分为笔试,性格测试,面试,综合面试,回学校等结果。笔试来说,华为的难度较中等,选择题难度和网易腾讯差不多。最后的代码题,相比下来就简单很多,一共3道题目,前2题很容易就AC,题目已经记不太清楚,不过难度确实不大。最后一题最后提交的代码过了75%的样例,一直没有发现剩下的25%可能存在什么坑。 笔试部分太久远,我就不怎么回忆了。直接将面试。 面试 如果说腾讯的面试是挥金如土...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

HTTP与HTTPS的区别

面试官问HTTP与HTTPS的区别,我这样回答让他竖起大拇指!

程序员毕业去大公司好还是小公司好?

虽然大公司并不是人人都能进,但我仍建议还未毕业的同学,尽力地通过校招向大公司挤,但凡挤进去,你这一生会容易很多。 大公司哪里好?没能进大公司怎么办?答案都在这里了,记得帮我点赞哦。 目录: 技术氛围 内部晋升与跳槽 啥也没学会,公司倒闭了? 不同的人脉圈,注定会有不同的结果 没能去大厂怎么办? 一、技术氛围 纵观整个程序员技术领域,哪个在行业有所名气的大牛,不是在大厂? 而且众所...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

终于懂了TCP和UDP协议区别

终于懂了TCP和UDP协议区别

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《C语言函数速查》main()主函数

每一个C程序都必须有一main()函数, 可以根据自己的爱好把它放在程序的某个地方。有些程序员把它放在最前面, 而另一些程序员把它放在最后面, 无论放在哪个地方, 以下几点说明都是适合的。

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

立即提问
相关内容推荐