java中事务未提交,但是在update之后再select为什么会得到update之后的结果?

想知道为什么会这样?
代码如下:


public static void main(String[] args) {
        String dbName = "F:/firstdb";

        String driver = "org.apache.derby.jdbc.EmbeddedDriver";

        String protocol = "jdbc:derby:";

        try{
            Class.forName(driver).newInstance();
            System.out.println("Loaded the appropriate driver");

            Connection conn = DriverManager.getConnection(protocol + dbName + ";");
            System.out.println("Connected to and created database " + dbName);

            conn.setAutoCommit(false);
            Statement stat = conn.createStatement();
            String command = "update my_test set NAME='1234' where ID='03'";
            stat.executeUpdate(command);
            //conn.rollback();


            PreparedStatement state = conn.prepareStatement("select * from my_test", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

            ResultSet rs = state.executeQuery();

            int i = 1;
            while(rs.next()){
                if(i < 4){
                    System.out.printf(rs.getString(1) + " ");
                    System.out.printf(rs.getString(2) + " ");
                    System.out.printf(rs.getString(3) + " ");
                    System.out.printf(rs.getString(4) + "\n");
                    i++;
                }else{
                    rs.relative(-2);
                    System.out.println("finally");
                    System.out.printf(rs.getString(1) + " ");
                    System.out.printf(rs.getString(2) + " ");
                    System.out.printf(rs.getString(3) + " ");
                    System.out.printf(rs.getString(4) + "\n");
                    break;
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }

结果如下:

 Loaded the appropriate driver
Connected to and created database F:/firstdb
01 男 10 LiSi
02 女 20 ZhangSan
03 男 40 1234
finally
02 女 20 ZhangSan

如果把update相关语句注释掉,那么结果如下:

 Loaded the appropriate driver
Connected to and created database F:/firstdb
01 男 10 LiSi
02 女 20 ZhangSan
03 男 40 123
finally
02 女 20 ZhangSan

8个回答

你这是没有明白什么叫事务,在数据库事务是指作为单个逻辑工作单元执行的一系列操作,要么完全地执行,要么完全地不执行,这是一种机制,用以维护数据库的完整性。在你这个事务单元中存在两个操作,一个是update,一个是select;你前面的update执行成功了,再执行select肯定能够查询到前面update的数据,因为你是在一个单元中。但是另外一个事务(即另一个单元)则不能select到这个update的数据,因为你update的数据还没提交,只在该单元中有效

czh500
lay500 回复weixin_38138163: 这不太可能吧,在同一个事务中,针对一条数据先查询,再修改,再查询,最后查询的结果理论上和第一次查询的结果应该不一样才对,除非你是如下这样写,举个例子,SELECT * FROM emp; UPDATE emp SET ename = '杨过' WHERE empno = 7900; ROLLBACK; SELECT * FROM emp; (即你在修改语句后面加了ROLLBACK;回滚关键字)
10 个月之前 回复
czh500
lay500 回复weixin_38138163: 这不太可能吧,在同一个事务中,针对一条数据先查询,再修改,再查询,最后查询的结果理论上和第一次查询的结果应该不一样才对,除非你是如下这样写,举个例子,SELECT * FROM emp; UPDATE emp SET ename = '杨过' WHERE empno = 7900; ROLLBACK; SELECT * FROM emp;
10 个月之前 回复
weixin_38138163
weixin_38138163 拿为什么在一个事务中,针对一条数据先查询,在修改,再查询,最后查询的结果是第一次查询的,而不是修改之后的值
12 个月之前 回复
yecunsb10049
土成 明白了,感谢回答!
大约 3 年之前 回复

你这是在同一个事务中进行的操作,虽然没有存入数据库,然是更改和查询的数据是同一条,每次执行完一次后应该关闭连接

czh500
lay500 回复土成: conn.setAutoCommit(false);这句话表示手动提交事务,你的update语句和select语句是在同一个事务中,所以,尽管你把conn.rollback();回滚的这句话注释掉了,update语句和select还是处于同一个事务中,所以update做的修改,select是可以看到update修改后的结果的,你可以这样测试一下,打开你的PLSQL Developer软件工具,在该软件工具中写上如下语句update my_test set NAME='1234' where ID='03';select * from my_test;然后执行,然后你看到的就是查询是修改后的效果,尽管你对这2句话,没有提交也没有回滚,但是,你如果打开一个新的PLSQL Developer软件窗口,在新窗口中输入select * from my_test;执行该语句的话,查询到的就是update更新前的数据,因为你新打开一个PLSQL Developer软件工具,就意味着这是一个新的连接,即一个新的会话,即这是一个新的事务,事务的隔离指的是不同事务之间的隔离,而不是指同一个事务内的隔离,同一个事务压根不存在隔离的说法
10 个月之前 回复
yecunsb10049
土成 明白了,感谢回答!
大约 3 年之前 回复

事务是隔离不同事务操作对同一数据的读写,你可以了解下事务的四个特性

就像楼上说的,事务的隔离性指的是两个事物之间。在同一事务中不存在隔离

你的update和select是处于同一个事务当中

而是她的衣服估计

conn.setAutoCommit(false);你设置了手动提交事务,必须要有跟他配对的commit或者是rollback,否则在这个连接既conn关闭之前,所有格update,insert,delete都是无效的,如果你把上面的conn.setAutoCommit(false);注释掉,效果就是修改了的。

conn.setAutoCommit(false);这句话表示手动提交事务,你的update语句和select语句是在同一个事务中,所以,尽管你把conn.rollback();回滚的这句话注释掉了,update语句和select还是处于同一个事务中,所以update做的修改,select是可以看到update修改后的结果的,你可以这样测试一下,打开你的PLSQL Developer软件工具,在该软件工具中写上如下语句update my_test set NAME='1234' where ID='03';select * from my_test;然后执行,然后你看到的就是查询是修改后的效果,尽管你对这2句话,没有提交也没有回滚。
但是,我们可以接着测试,你可以打开一个新的PLSQL Developer软件窗口,在新窗口中输入select * from my_test;执行该语句的话,查询到的就是update更新前的数据,因为你新打开一个PLSQL Developer软件工具,就意味着这是一个新的连接,即这是一个新的会话,即这是一个新的事务,事务的隔离指的是不同事务之间的隔离,而不是指同一个事务内的隔离,同一个事务内压根不存在隔离的说法

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
请问sql语句在select前为什么要先update一下,这样能保证并发时数据一致吗?
背景介绍:db2数据库,jdbc连接,java类用sql语句操作数据库。 功能介绍:一张表专门用于存储流水号,这个流水号递增。由于是web程序,可能有很高的并发性。 我们保证每个人如果想得到流水号,流水号不会重复。 语句大概如下: 第1行:sql="update table1 set serialno=serialno where id=1";(这行的两个serialno都是table1 的属性) 第2行:sql="select serialno from table1 where id=1"; 第3行:将上面得到的serialno加上1存入newSerialno变量中; 第4行:sql="update table1 set serialno='"+newSerialno+"' where id=1";(这行的newSerialno是变量) 这4行都是在同一个事务中(transaction); 我不明白的地方是:为什么要用第1行?执行这句对数据库不进行任何修改,难道这样就能够保证并发时流水号不重复。 请牛人帮忙,能解释详细点更好!
Springboot+JDBCTemplete+MySQL InnoDB+druid连接池事务出问题
方法如下: tb_counter中只有一行记录,用作计数器变量,每次执行gogo会将其加100 然后将其值插入tb_block 可重复读情况下,单个访问没问题,但并发访问总是抛异常说:插入tb_block时主键值重复 System.out输出的num也重复了 理论上num应该在事务中锁定,每次增加100,应该不可能有重复的才对啊 log中事务也显示正常开启和完成 但把druid连接数设置为1时,就不会出现这个问题 把事务隔离级别设置为最高时也不会出现,但是会老抛异常说死锁 mysql重启了,也一样,数据库清了也一样。。。。。 生无可恋。。。。 ```java @Autowired JdbcTemplate jdbct; @Transactional(propagation=Propagation.REQUIRED) public String gogo() { Long num=jdbct.queryForObject("SELECT num FROM tb_counter WHERE id = 0",Long.class); System.out.println(num); jdbct.update("INSERT INTO tb_block(id,state) VALUE("+num+",'DNF')"); jdbct.update("UPDATE tb_counter SET num="+(num+100)+" WHERE id = 0"); return num.toString(); } } ```
Spring事务的问题,bulkUpdate,或query.executeUpdate
今天在测试spring任务调度时,突然发现我配的声明事务不起作用了,找了好久才发现不是我的事务的问题,是我在Dao中用了一个方法有问题 方法如下: public void updateByIds(final Set<String> updateIds)throws DaoException{ try { String queryString="update from Yaoyueyingyue y set y.state='2' where y.yaoyueid in (?)"; getHibernateTemplate().bulkUpdate(queryString, updateIds.toArray()); } catch (Exception e) { e.printStackTrace(); throw new DaoException(this.getClassName()+e.getMessage()); } updateIds是一个包含要更新的编号集合,我发现用这个方法在我Manager中调用Dao事务就不起作用了,后来又改成这样 public void updateByIds(final Set<String> updateIds)throws DaoException{ try { getHibernateTemplate().execute(new HibernateCallback(){ final String hql="update Yaoyueyingyue y set y.state=2 where yaoyueid in (:yaoyueid)"; public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery(hql); query.setParameterList("yaoyueid", updateIds); query.executeUpdate(); return null; } }); } catch (Exception e) { e.printStackTrace(); throw new DaoException(this.getClassName()+e.getMessage()); } } 事务还是不行,这两个方法好像不受spring AOP事务管理,只要执行到这个Dao的方法就自动提交了,出来异常也不能回滚,真是郁闷,小弟对这块不是很明白,为什么事务就不行了呢,希望那位牛人,帮我解释下,谢谢了, 我的spring声明事务大概如下: <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close"> <property name="forceShutdown"> <value>true</value></property> </bean> <bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp"> <property name="transactionTimeout" value="300"/> </bean> <bean id="springTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManager"><ref bean="atomikosTransactionManager" /></property> <property name="userTransaction"><ref bean="atomikosUserTransaction" /></property> </bean> <aop:config> <!-- This definition creates auto-proxy infrastructure based on the given pointcut, expressed in AspectJ pointcut language. Here: applying the advice named "txAdvice" to all methods on classes named PetStoreImpl. --> <aop:advisor pointcut="execution(* com.goal.log.manager.*.*(..))" advice-ref="txAdvice" /> <aop:advisor pointcut="execution(* com.goal.system.manager.*.*(..))" advice-ref="txAdvice" /> </aop:config> <!-- @Transactional 时要使用下面一行 --> <!-- <tx:annotation-driven transaction-manager="springTransactionManager" proxy-target-class="true"/> --> <!-- Transaction advice definition, based on method name patterns. Defaults to PROPAGATION_REQUIRED for all methods whose name starts with "insert" or "update", and to PROPAGATION_REQUIRED with read-only hint for all other methods.--> <!-- 引用springTransactionManager --> <tx:advice id="txAdvice" transaction-manager="springTransactionManager"> <tx:attributes> <tx:method name="save*" rollback-for="java.lang.Exception"/> <tx:method name="insert*" rollback-for="java.lang.Exception"/> .... <tx:method name="*" read-only="true" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> atomikosTransactionManager这个东西不用管,是一个开源的支持JTA分布式的JAR,希望有人能够为我解答........ [b]问题补充:[/b] 谢谢你的解答,但是我还是不明白你的意思,你是指我的Dao中用了内部类吗,你所指的 “调用updateByIds方法 的代码 跳出你的当前类 然后在别的类调用当前了类的接口中的方法updateByIds ”是指什么意思,能不能说明白点,谢谢了!!! [b]问题补充:[/b] 谢谢你的答复,你的意思我也理解,但好像不是这个问题,因为我并没有像你说的那样在类的内部调用,我的所有方法都是在业务逻辑层调用的Manager层,Manager层我是在Spring中配置了的声明事务的,我给你据个例子: 这两个方法都是Dao中的 方法一: [code="java"] public void updateByIds(final Set<String> updateIds)throws DaoException{ try { /*String queryString="update from Yaoyuepub y set y.state='2' where y.yaoyueid in (?)"; getHibernateTemplate().bulkUpdate(queryString, updateIds.toArray());*/ getHibernateTemplate().execute(new HibernateCallback(){ final String hql="update Yaoyuepub y set y.state=2 where yaoyueid in (:yaoyueid)"; public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery(hql); query.setParameterList("yaoyueid", updateIds); query.executeUpdate(); return null; } } ); } catch (Exception e) { e.printStackTrace(); throw new DaoException(this.getClassName()+e.getMessage()); } } [/code] 这个方法是把所有的要改的ID都一次性更新调,我是不想执行多条sql,在Manager中调用这个方法事务就起不了作用,还有一个方法,就是普通的更新对象 [code="java"] public void update(T t) throws DaoException { try { getHibernateTemplate().update(t); } catch (Exception e) { throw new DaoException(getClassName() + " update exception...",e); } } [/code] 要是把刚才Manager中调用改成循环执行下面的方法一个一个对象,就是有事务的,所以调用都一样,更类的内部调用应给没有关系的,我认为不管是query.executeUpdate还是spring自己提供的bulkUpdate这两个方法都是要写sql的,目的是满足批量更新和更大的灵活性,但是事务就不行了,我认为肯定可以让声明式事务支持这两个方法,就是不知道怎么配置一下,你可以自己在代码中分别做个例子试试,看看是不是用批量更新事务就控制不了了, 这就是我的理解,还请多多指教,谢谢诶!!! [b]问题补充:[/b] 我测试过了,以为可以了,但是还是不行,下面是我调用的一小部分代码 [code="java"] public void runThread() { Set<String> updateIds = new HashSet<String>(); for (Yaoyueyingyue yaoyueyingyue : yaoyueyingyues) { updateIds.add(yaoyueyingyue.getYaoyueid()); } if (updateIds.size() > 0) { yaoyuepubDao.updateByIds(updateIds); if(true) throw new RuntimeException("AAAAAAAAAAAAAAAAAAAAAAAAA"); yaoyueyingyueDao.updateByIds(updateIds); } [/code] 上面是我Manager中Spring任务调度自动执行的方法的一小部分,我中间估计抛出了异常,但是yaoyuepubDao数据库中都更新了,事务不起作用,我估计其实就是和bulkUpdate方法一样,只要这个方法能用事务控制了的话,应该没问题了 [b]问题补充:[/b] 下面是我在网上拷贝的--------------------------------   Spring的HibernateTemplate提供了Hibernate的完美封装,即通过匿名类实现回调,来保证Session的自动资源管理和事务的管理。其中核心方法是:   java代码: HibernateTemplate.execute(new HibernateCallback() {  public Object doInHibernate(Session session) throws HibernateException {   ....  } }   回调方法提供了session作为参数,有了session,就可以自由的使用Hibernate API编程了。使用了spring的之后,代码修改如下:   web层代码:   java代码: DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Department.class); detachedCriteria.createAlias("employees", "e").add(Restrictions.eq("name", "department")).add(Restrictions.gt(("e.age"), new Integer(20))); departmentManager.findByCriteria(detachedCriteria);   构造detachedCriteria,作为参数传递给departmentManager   业务层代码使用spring,DepartmentManager的findByCriteria如下:   java代码: public List findByCriteria(final DetachedCriteria detachedCriteria) {  return (List) getHibernateTemplate().execute(new HibernateCallback() {   public Object doInHibernate(Session session) throws HibernateException {    Criteria criteria = detachedCriteria.getExecutableCriteria(session);    return criteria.list();   }  }); }   实际上也就是:   java代码: Criteria criteria = detachedCriteria.getExecutableCriteria(session); return criteria.list();   而已   但是该程序代码执行,会抛出强制类型转换异常!   我跟踪了一下spring和Hibernate源代码,原因如下:   spring的HibernateTemplate的execute方法提供的回调接口具有Session作为参数,但是实际上,默认情况下,HibernateTemplate传递给回调接口的session并不是org.hibernate.impl.SessionImpl类,而是SessionImpl类的一个Proxy类。之所以替换成为一个Proxy类,HibernateTemplate的注释说明,Proxy提供了一些额外的功能,包括自动设置Cachable,Transaction的超时时间,Session资源的更积极的关闭等等。   java代码: private boolean exposeNativeSession = false; ...   execute方法内部: Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session));   但是遗憾的是,Hibernate的DetachedCriteria的setExecutableCriteria方法却要求将session参数强制转为SessionImpl,但是spring传过来的却是一个Proxy类,因此就报错了。   java代码: public Criteria getExecutableCriteria(Session session) {  impl.setSession( (SessionImpl) session ); // 要求SessionImpl,Spring传递的是Proxy  return impl; }   解决方法,禁止Spring的HibernateTemplate传递Proxy类,强制要求它传递真实的SessionImpl类,即给exexute方法增加一个参数,提供参数为true,如下:   java代码: public List findByCriteria(final DetachedCriteria detachedCriteria) {  return (List) getHibernateTemplate().execute(new HibernateCallback() {   public Object doInHibernate(Session session) throws HibernateException {    Criteria criteria = detachedCriteria.getExecutableCriteria(session);    return criteria.list();   }  }, true); } [b]问题补充:[/b] bulkUpdate这个方法按你给的源码,那我是用错了,但是你所说的我的模拟异常不再AOP的事务之内,我就不同意你的观点了,[code="java"] if (updateIds.size() > 0) { yaoyuepubDao.updateByIds(updateIds); // 事务开启 执行updateByIds 事务提交 if(true) throw new RuntimeException("AAAAAAAAAAAAAAAAAAAAAAAAA"); yaoyueyingyueDao.updateByIds(updateIds); // 事务开启 执行updateByIds 事务提交 } [/code] 我这段代码是两个Dao的操作,而这两个Dao的操作是被封装在一个Manger中的方法中的,Manager的每个方法都是有事务的,在操作玩第一个Dao后抛出一个RunTime异常,这时候第一个Dao操作已经执行了,这时候事务应该回滚的,不应该去更新的第一个Dao的操作,Manager中本来就业务层,中间有好多的Dao操作,事务应该控制这些Dao要不都提交,要不都回滚,你说呢,而你说的在11-12行之间加异常,那在一个Dao中,再说的的Dao是没有配事务的,又何谈回滚呢,要是把我上面两个Dao操作改成普通的对象更新,是可以回滚的,这个我肯定 比如这样 [code="java"] yaoyuepubDao.update(yaoyuepub); if(true) throw new RuntimeException("AAAAAAAAAAAAAAAAAAAAAAAAA"); yaoyueyingyueDao.update(yaoyueyingyue); [/code] 这个时候如果抛出异常,yaoyuepub是不会更新到数据库的,会回滚的,所以我总结就是executeUpdate(sql)这个方法我们直接sql,和操作对象是不一样的的,具体我也没有研究 [b]问题补充:[/b] [code="java"] public void updateByIds(final Set<String> updateIds)throws DaoException{ try { getHibernateTemplate().execute(new HibernateCallback(){ final String hql="update Yaoyuepub y set y.state=2 where yaoyueid in (:yaoyueid)"; public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query=session.createQuery(hql); query.setParameterList("yaoyueid", updateIds); query.executeUpdate(); return null; } } , true); } catch (Exception e) { e.printStackTrace(); throw new DaoException(this.getClassName()+e.getMessage()); } } [/code] 把上面的updateIds方法改成: [code="java"] public void updateByIds(final Set<String> updateIds)throws DaoException{ try { DetachedCriteria dc=DetachedCriteria.forClass(Yaoyuepub.class); dc.add(Restrictions.in("yaoyueid", updateIds)); List<Yaoyuepub> yaoyuepubs=select(dc); for(Yaoyuepub y:yaoyuepubs){ update(y); } } catch (Exception e) { e.printStackTrace(); throw new DaoException(this.getClassName()+e.getMessage()); } } [/code] 所有的调用都不变,spring事务就起作用了,说明自己createQuery然后executeUpdate是不被事务管理的,后其他都没有关系
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>
请教一下,到底我的mapper.xml哪里出错了,弄不明白为什么找不到我写的log类
## update一下经大佬提点后如何解决的 可能因为我曾用粗暴的方法改动过Log.java的类名,导致Log类编译出问题了,编译后类文件夹内根本没有Log.class文件。于是我又粗暴地delete了Log类重写了一次,果然没问题了。 顺便百度了一下如何修改类名 https://zhidao.baidu.com/question/340215163.html ## 原问题如下 小白入门程序媛,这个是一个mybatis的关于银行转账的小练习 在写log部分之前,我写的account部分测试过是没有问题的,转账的业务也成功了的。现在是想增加一个记录日志的操作,在数据库log表格添加转账记录,并且利用log4j在硬盘生成log file中记录转账信息。 可是按照同样的套路写了了log实体类后再写logmapper.xml,却出现了以下的错误,后来干脆连mybatis中的别名的部分都去掉了,直接在mapper.xml中使用完整的类名,还是说找不到我写的log类。实在搞不懂是namespace出错了还是怎么滴。。。。 ## 错误信息如下: ``` 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Server version: Apache Tomcat/8.5.42 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Server built: Jun 4 2019 20:29:04 UTC 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Server number: 8.5.42.0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: OS Name: Windows 10 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: OS Version: 10.0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Architecture: amd64 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Java Home: C:\Program Files\Java\jdk1.8.0_201\jre 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: JVM Version: 1.8.0_201-b09 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: JVM Vendor: Oracle Corporation 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: CATALINA_BASE: D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: CATALINA_HOME: D:\apache-tomcat-8.5.42 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dcatalina.base=D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dcatalina.home=D:\apache-tomcat-8.5.42 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dwtp.deploy=D:\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Djava.endorsed.dirs=D:\apache-tomcat-8.5.42\endorsed 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.VersionLoggerListener log 信息: Command line argument: -Dfile.encoding=UTF-8 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: Loaded APR based Apache Tomcat Native library [1.2.21] using APR version [1.6.5]. 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true]. 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent 信息: APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true] 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.AprLifecycleListener initializeSSL 信息: OpenSSL successfully initialized [OpenSSL 1.1.1a 20 Nov 2018] 七月 13, 2019 8:47:00 下午 org.apache.coyote.AbstractProtocol init 信息: Initializing ProtocolHandler ["http-nio-8080"] 七月 13, 2019 8:47:00 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector 信息: Using a shared selector for servlet write/read 七月 13, 2019 8:47:00 下午 org.apache.coyote.AbstractProtocol init 信息: Initializing ProtocolHandler ["ajp-nio-8009"] 七月 13, 2019 8:47:00 下午 org.apache.tomcat.util.net.NioSelectorPool getSharedSelector 信息: Using a shared selector for servlet write/read 七月 13, 2019 8:47:00 下午 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 828 ms 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.StandardService startInternal 信息: Starting service [Catalina] 七月 13, 2019 8:47:00 下午 org.apache.catalina.core.StandardEngine startInternal 信息: Starting Servlet Engine: Apache Tomcat/8.5.42 七月 13, 2019 8:47:01 下午 org.apache.jasper.servlet.TldScanner scanJars 信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 七月 13, 2019 8:47:02 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["http-nio-8080"] 七月 13, 2019 8:47:02 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["ajp-nio-8009"] 七月 13, 2019 8:47:02 下午 org.apache.catalina.startup.Catalina start 信息: Server startup in 1377 ms 七月 13, 2019 8:47:32 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [yan.ibbie.servlet.TransferServlet] in context with path [/bank] threw exception org.apache.ibatis.exceptions.PersistenceException: ### Error building SqlSession. ### The error may exist in yan/ibbie/mapper/logmapper.xml ### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'yan/ibbie/mapper/logmapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:80) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:64) at yan.ibbie.service.Impl.AccountServiceImpl.transfer(AccountServiceImpl.java:23) at yan.ibbie.servlet.TransferServlet.service(TransferServlet.java:36) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'yan/ibbie/mapper/logmapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:121) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parse(XMLConfigBuilder.java:99) at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:78) ... 26 more Caused by: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'yan/ibbie/mapper/logmapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:120) at org.apache.ibatis.builder.xml.XMLMapperBuilder.parse(XMLMapperBuilder.java:92) at org.apache.ibatis.builder.xml.XMLConfigBuilder.mapperElement(XMLConfigBuilder.java:373) at org.apache.ibatis.builder.xml.XMLConfigBuilder.parseConfiguration(XMLConfigBuilder.java:119) ... 28 more Caused by: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:118) at org.apache.ibatis.builder.xml.XMLStatementBuilder.parseStatementNode(XMLStatementBuilder.java:68) at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildStatementFromContext(XMLMapperBuilder.java:135) at org.apache.ibatis.builder.xml.XMLMapperBuilder.buildStatementFromContext(XMLMapperBuilder.java:128) at org.apache.ibatis.builder.xml.XMLMapperBuilder.configurationElement(XMLMapperBuilder.java:118) ... 31 more Caused by: org.apache.ibatis.type.TypeException: Could not resolve type alias 'yan.ibbie.pojo.Log'. Cause: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:120) at org.apache.ibatis.builder.BaseBuilder.resolveAlias(BaseBuilder.java:149) at org.apache.ibatis.builder.BaseBuilder.resolveClass(BaseBuilder.java:116) ... 35 more Caused by: java.lang.ClassNotFoundException: Cannot find class: yan.ibbie.pojo.Log at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:200) at org.apache.ibatis.io.ClassLoaderWrapper.classForName(ClassLoaderWrapper.java:89) at org.apache.ibatis.io.Resources.classForName(Resources.java:261) at org.apache.ibatis.type.TypeAliasRegistry.resolveAlias(TypeAliasRegistry.java:116) ... 37 more ``` ## mybatis.xml如下: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <!-- default填默认使用的environment的id --> <environments default="default"> <!-- environment标签声明一个环境 --> <environment id="default"> <!-- type="JDBC"表示使用原生JDBC事务 --> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8"/> <property name="username" value="root"/> <property name="password" value="1233210"/> </dataSource> </environment> </environments> <mappers> <mapper resource="yan/ibbie/mapper/accountmapper.xml"/> <mapper resource="yan/ibbie/mapper/logmapper.xml"/> </mappers> </configuration> ``` ## accountmapper.xml如下: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="yan.ibbie.mapper.accountmapper"> <!-- 根据账号和密码查询账户信息 --> <select id="selByAccnoPassword" resultType="yan.ibbie.pojo.Account" parameterType="yan.ibbie.pojo.Account"> select * from account where accno=#{accNo} and password=#{password} </select> <!-- 根据账号和姓名查询账户信息 --> <select id="selByAccnoName" resultType="yan.ibbie.pojo.Account" parameterType="yan.ibbie.pojo.Account"> select * from account where accno=#{accNo} and name=#{name} </select> <!-- 根据账号修改账户余额 --> <update id="updBalanceByAccno" parameterType="yan.ibbie.pojo.Account"> update account set balance=balance+#{balance} where accno=#{accNo} </update> </mapper> ``` ## logmapper.xml如下: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="yan.ibbie.mapper.logmapper"> <insert id="insLog" parameterType="yan.ibbie.pojo.Log"> insert into log values(default,#{accOut},#{accIn},#{money}) </insert> </mapper> ``` ## yan.ibbie.pojo.log如下 ``` package yan.ibbie.pojo; public class Log { private int id; private String accOut; private String accIn; private double money; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAccOut() { return accOut; } public void setAccOut(String accOut) { this.accOut = accOut; } public String getAccIn() { return accIn; } public void setAccIn(String accIn) { this.accIn = accIn; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } } ``` ## AccountServiceImpl如下: ``` package yan.ibbie.service.Impl; import java.io.IOException; import java.io.InputStream; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.sun.istack.internal.logging.Logger; import yan.ibbie.pojo.Account; import yan.ibbie.pojo.Log; import yan.ibbie.service.AccountService; public class AccountServiceImpl implements AccountService { @Override public int transfer(Account accIn, Account accOut) throws IOException { InputStream is = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); SqlSession session = factory.openSession(); Account accOutSelect = session.selectOne("yan.ibbie.mapper.accountmapper.selByAccnoPassword",accOut); if (accOutSelect!=null) { if(accOutSelect.getBalance()>=accOut.getBalance()) { Account accInSelect = session.selectOne("yan.ibbie.mapper.accountmapper.selByAccnoName",accIn); if (accInSelect!=null) { accIn.setBalance(accOut.getBalance()); accOut.setBalance(-accOut.getBalance()); int index=session.update("yan.ibbie.mapper.accountmapper.updBalanceByAccno", accOut); index += session.update("yan.ibbie.mapper.accountmapper.updBalanceByAccno",accIn); if (index==2) { Log log = new Log(); log.setAccOut(accOut.getAccNo()); log.setAccIn(accIn.getAccNo()); log.setMoney(accIn.getBalance()); session.update("yan.ibbie.mapper.logmapper.insLog", log); Logger logger = Logger.getLogger(AccountServiceImpl.class); logger.info(log.getAccOut()+"给"+log.getAccIn()+ "在"+new Date().toLocaleString()+"转了"+log.getMoney()); session.commit(); session.close(); return SUCCESS; }else { session.rollback(); session.close(); return ERROR; } }else { return ACCOUNT_NAME_NOT_MATCH; } }else { return ACCOUNT_BALANCE_NOT_ENOUGHT; } }else { return ACCOUNT_PASSWORD_NOT_MATCH; } } } ```
hibernate及spring的一些细节问题
<p>关于update方法有几个地方不明白。 <br><br><br><br><br>类似上面的方法,调用 select 方法查询出一个实体类对象,方法外部对该对象进行修改,然后传入 update 方法修改。 <br><br>由于 select 和 update 使用的是两个独立的session,所以调用 session.update 方法的时候会抛出异常,因为传入的obj状态属于托管状态,不是持久态,是这样没错吧。 <br><br></p> <pre name="code" class="java">public Object doSelectXXX(){ Session session = HibernateUtil.getSession(); Object result = session.get(....); session.close(); return result; } public boolean doUpdateXXX(Object obj){ Session session = HibernateUtil.getSession(); session.beginTr....(); session.update(obj); // commit session.close(); return true; } /*类似上面的方法,调用 select 方法查询出一个实体类对象,方法外部对该对象进行修改,然后传入 update 方法修改。 由于 select 和 update 使用的是两个独立的session,所以调用 session.update 方法的时候会抛出异常,因为传入的obj状态属于托管状态,不是持久态,是这样没错吧。*/ /* 下面是我的问题,在spring里集成了hibernate。使用hibernatetemplate类进行操作,配置了相应的事务,并且设置事务隔离级别为:REQUIRES_NEW,总是开启一个新的事务,我理解的spring对session事务的管理应该是方法执行之前打开事务,方法执行之后提交事务,同时关闭session,那么这就和以上的类似了。 按我预想的应该是会抛出异常的,但是却没有,不知道我哪里理解错了? 以下是spring集成hibernate之后的简略代码。 */ public Object doSelectXXX(){ return getHibernateTemplate().get(......); } public boolean doUpdateXXX(Object obj){ getHibernateTemplate().update(obj); return true; }</pre> <p> </p> <p> </p>
spring+ibatis 事务错误
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentdao' defined in URL [file:/E:/资料/apache-tomcat-6.0.29/webapps/firstibatis/WEB-INF/classes/spring/applicationContext-jdbc.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'driverClassName' of bean class [dao.impl.StudentDaoImpl]: Bean property 'driverClassName' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1427) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1132) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522) 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:607) 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:383) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4135) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4630) 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:546) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1041) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:964) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardHost.start(StandardHost.java:785) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445) at org.apache.catalina.core.StandardService.start(StandardService.java:519) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) xml配置文件如下: <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1/student"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!--配置哪些方法,什么情况下需要回滚--> <tx:advice id="serviceAdvice" transaction-manager="txManager"> <tx:attributes> <!--当代理的service层中的方法抛出异常的时候才回滚,必须加rollback-for参数--> <tx:method name="insert*" propagation="REQUIRED" rollback-for="Throwable"/> <tx:method name="del*" propagation="REQUIRED" rollback-for="Throwable"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="Throwable"/> <!--除了上面标识的方法,其他方法全是只读方法 --> <tx:method name="*" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置哪些类的方法需要进行事务管理 --> <aop:config proxy-target-class="true"> <aop:pointcut id="servicePointcut" expression="execution(* dao.impl.*.*(..))"/> <aop:advisor pointcut-ref="servicePointcut" advice-ref="serviceAdvice"/> </aop:config> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation"><value>classpath:config/jdbc/sqlMapConfig.xml</value></property> </bean> <bean id="studentdao" class="dao.impl.StudentDaoImpl"> <property name="sqlMapClient" ref="sqlMapClient"></property> </bean> <bean id="studentmanager" class="manager.impl.StudentManagerImpl"> <property name="studentdao" ref="studentdao"></property> </bean> studentdaoimpl public class StudentDaoImpl extends SqlMapClientDaoSupport implements StudentDao{ @Override public List<Student> getAllStudent() { // TODO Auto-generated method stub return null; } @Override public Student getStudentById(String id) { // TODO Auto-generated method stub return null; } @Override public List<Object> select(String name) throws Exception { // TODO Auto-generated method stub return null; } @Override public List<Student> selects(Map map) throws Exception { // TODO Auto-generated method stub return null; } @Override public void tianjia(Map map) throws Exception { // TODO Auto-generated method stub } @Override public void update(Map map) throws Exception { // TODO Auto-generated method stub } }
org.apache.ibatis.exceptions.PersistenceException怎么解决?
调试一个开源项目出现报错,项目所有sql都会报空指针异常 ``` 严重: Servlet.service() for servlet [springMvc] in context with path [/mallapp] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.lang.NullPointerException ### The error may exist in file [H:\WorksSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\mallapp\WEB-INF\classes\mybatis\category\CategoryMapper.xml] ### The error may involve CategoryMapper.listAll-Inline ### The error occurred while setting parameters ### SQL: select category_name, category_img, sort, category_id, super_id from shop_category where super_id =? order by sort ### Cause: java.lang.NullPointerException] with root cause java.lang.NullPointerException at org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:43) at org.apache.ibatis.scripting.defaults.DefaultParameterHandler.setParameters(DefaultParameterHandler.java:81) at org.apache.ibatis.executor.statement.PreparedStatementHandler.parameterize(PreparedStatementHandler.java:80) at org.apache.ibatis.executor.statement.RoutingStatementHandler.parameterize(RoutingStatementHandler.java:61) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:62) at com.sun.proxy.$Proxy84.parameterize(Unknown Source) at org.apache.ibatis.executor.ReuseExecutor.prepareStatement(ReuseExecutor.java:79) at org.apache.ibatis.executor.ReuseExecutor.doQuery(ReuseExecutor.java:56) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:267) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:137) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:96) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:77) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:108) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:102) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358) at com.sun.proxy.$Proxy74.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198) at com.yq.dao.DaoSupport.findForList(DaoSupport.java:118) at com.yq.service.category.impl.CategoryService.listAll(CategoryService.java:62) at com.yq.service.category.impl.CategoryService$$FastClassBySpringCGLIB$$51d95cd7.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644) at com.yq.service.category.impl.CategoryService$$EnhancerBySpringCGLIB$$c2253a36.listAll(<generated>) at com.yq.controller.category.CategoryController.list(CategoryController.java:80) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) ``` CategoryMapper.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="CategoryMapper"> <!--表名 --> <sql id="tableName"> shop_category </sql> <!-- 字段 --> <sql id="Field"> category_name, category_img, sort, category_id, super_id </sql> <!-- 字段值 --> <sql id="FieldValue"> #{category_name}, #{category_img}, #{sort}, #{category_id}, #{super_id} </sql> <!-- 新增--> <insert id="save" parameterType="pd"> insert into <include refid="tableName"></include> ( <include refid="Field"></include> ) values ( <include refid="FieldValue"></include> ) </insert> <!-- 删除--> <delete id="delete" parameterType="pd"> delete from <include refid="tableName"></include> where category_id = #{category_id} </delete> <!-- 修改 --> <update id="edit" parameterType="pd"> update <include refid="tableName"></include> set category_name = #{category_name}, category_img = #{category_img}, sort = #{sort} where category_id = #{category_id} </update> <!-- 通过ID获取数据 --> <select id="findById" parameterType="pd" resultType="pd"> select <include refid="Field"></include> from <include refid="tableName"></include> where category_id = #{category_id} </select> <!-- 列表 --> <select id="datalistPage" parameterType="page" resultType="pd"> select <include refid="Field"></include> from <include refid="tableName"></include> where 1=1 and super_id =#{pd.super_id} order by sort </select> <!-- 列表(全部) --> <select id="listAll" parameterType="pd" resultType="pd"> select <include refid="Field"></include> from <include refid="tableName"></include> where super_id =#{super_id} order by sort </select> <!-- 批量删除 --> <delete id="deleteAll" parameterType="String"> delete from <include refid="tableName"></include> where category_id in <foreach item="item" index="index" collection="array" open="(" separator="," close=")"> #{item} </foreach> </delete> </mapper> ``` mybatis-config.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 --> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> <!-- 打印查询语句 --> <setting name="logImpl" value="LOG4J" /> </settings> <typeAliases> <typeAlias type="org.change.entity.system.User" alias="User"/> <typeAlias type="org.change.entity.system.Role" alias="Role"/> <typeAlias type="org.change.entity.system.Menu" alias="Menu"/> <typeAlias type="org.change.entity.system.Dictionaries" alias="Dictionaries"/> <typeAlias type="org.change.entity.system.Department" alias="Department"/> <typeAlias type="org.change.util.PageData" alias="pd"/> <!-- 分页 --> <typeAlias type="org.change.entity.Page" alias="Page"/> </typeAliases> <plugins> <plugin interceptor="org.change.plugin.PagePlugin"> <property name="dialect" value="mysql"/> <property name="pageSqlId" value=".*listPage.*"/> </plugin> </plugins> </configuration> ``` DAO.java ``` public interface DAO { /** * 保存对象 * @param str * @param obj * @return * @throws Exception */ public Object save(String str, Object obj) throws Exception; /** * 修改对象 * @param str * @param obj * @return * @throws Exception */ public Object update(String str, Object obj) throws Exception; /** * 删除对象 * @param str * @param obj * @return * @throws Exception */ public Object delete(String str, Object obj) throws Exception; /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForObject(String str, Object obj) throws Exception; /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForList(String str, Object obj) throws Exception; /** * 查找对象封装成Map * @param s * @param obj * @return * @throws Exception */ public Object findForMap(String sql, Object obj, String key , String value) throws Exception; } ``` DaoSupport.java ``` @Repository("daoSupport") public class DaoSupport implements DAO { @Resource(name = "sqlSessionTemplate") private SqlSessionTemplate sqlSessionTemplate; /** * 保存对象 * @param str * @param obj * @return * @throws Exception */ public Object save(String str, Object obj) throws Exception { return sqlSessionTemplate.insert(str, obj); } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public Object batchSave(String str, List objs )throws Exception{ return sqlSessionTemplate.insert(str, objs); } /** * 修改对象 * @param str * @param obj * @return * @throws Exception */ public Object update(String str, Object obj) throws Exception { return sqlSessionTemplate.update(str, obj); } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public void batchUpdate(String str, List objs )throws Exception{ SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory(); //批量执行器 SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false); try{ if(objs!=null){ for(int i=0,size=objs.size();i<size;i++){ sqlSession.update(str, objs.get(i)); } sqlSession.flushStatements(); sqlSession.commit(); sqlSession.clearCache(); } }finally{ sqlSession.close(); } } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public Object batchDelete(String str, List objs )throws Exception{ return sqlSessionTemplate.delete(str, objs); } /** * 删除对象 * @param str * @param obj * @return * @throws Exception */ public Object delete(String str, Object obj) throws Exception { return sqlSessionTemplate.delete(str, obj); } /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForObject(String str, Object obj) throws Exception { return sqlSessionTemplate.selectOne(str, obj); } /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForList(String str, Object obj) throws Exception { return sqlSessionTemplate.selectList(str, obj); } public Object findForMap(String str, Object obj, String key, String value) throws Exception { return sqlSessionTemplate.selectMap(str, obj, key); } } ``` spring.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:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- 阿里 druid数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <!-- 数据库基本信息配置 --> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <property name="filters" value="${filters}" /> <!-- 最大并发连接数 --> <property name="maxActive" value="${maxActive}" /> <!-- 初始化连接数量 --> <property name="initialSize" value="${initialSize}" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${maxWait}" /> <!-- 最小空闲连接数 --> <property name="minIdle" value="${minIdle}" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testWhileIdle" value="${testWhileIdle}" /> <property name="testOnBorrow" value="${testOnBorrow}" /> <property name="testOnReturn" value="${testOnReturn}" /> <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="${removeAbandoned}" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="${logAbandoned}" /> </bean> <!-- 启用注解 --> <context:annotation-config /> <!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 --> <context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 注解方式配置事务--> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事务 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 事物处理 --> <aop:config> <aop:pointcut id="pc" expression="execution(* com.*.service..*(..))" /> <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" /> </aop:config> <!-- 配置mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- mapper扫描 --> <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory" /> </bean> </beans> ```
尝试写了一个 JDBC 操作 SQLServer 的工具类,但是好像有问题,求大神帮忙指正
java新人,尝试写了一个 JDBC 操作 SQLServer 的工具类,但是好像有问题,调用 insert 指令没问题,而 select 指令出现如下报错: com.microsoft.sqlserver.jdbc.SQLServerException: ')' 附近有语法错误。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515) at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:792) at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616) at com.javaee.servletxm.comm.MSSQLJDBC.select(MSSQLJDBC.java:160) at com.javaee.servletxm.comm.MSSQLJDBC.select(MSSQLJDBC.java:195) at com.javaee.servletxm.comm.MSSQLJDBC.selectFirstValue(MSSQLJDBC.java:172) at com.javaee.servletxm.comm.MSSQLJDBC.getPageNumber(MSSQLJDBC.java:221) at com.javaee.servletxm.comm.MSSQLJDBC.selectByFY(MSSQLJDBC.java:259) at com.javaee.servletxm.kqgl.KqManager.getAllKqxx(KqManager.java:38) at com.javaee.servletxm.kqgl.Kqwh.doGet(Kqwh.java:47) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) at javax.servlet.http.HttpServlet.service(HttpServlet.java:723) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760) at java.lang.Thread.run(Thread.java:724) 这是具体的代码,求大神帮忙指正 package com.javaee.servletxm.comm; /** * jdbc下 SQL Server 2005 数据库的封装类 */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties; public class MSSQLJDBC { // 配置文件名称 private String iniFileName = MSSQLJDBC.class.getClassLoader().getResource("/com/javaee/servletxm/comm").getPath()+ "mssql.properties"; // 连接数据库 private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; private String url = "jdbc:sqlserver://localhost;DatabaseName=jdms"; private String user = "sa"; private String password = ""; // 定义连接属性 private Connection connect = null; // 与连接有关三个通道 private Statement stmt = null; private PreparedStatement pstmt = null; private CallableStatement cstmt = null; public static final String stmtType = "stmt"; public static final String pstmtType = "pstmt"; public static final String cstmtType = "cstmt"; // 定义参数类型的静态常量值 public static final String varCharType = "varchar"; public static final String intType = "int"; public static final String doubleType = "decimal"; public static final String dateType = "datetime"; public static final String timeType = "timestamp"; // 定义全局的结果集 private ResultSet rs = null; // 在构造方法中对属性进行初始化赋值操作 public MSSQLJDBC() { // 读取配置文件 readIni(); // 初始化连接 initConnect(); } // 可配置文件 .properties // 读取配置文件 private void readIni() { File file = new File(iniFileName); if (!file.exists()) { // 创建一个文件 try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } // 判断文件是否有值 if (file.length() == 0) {// 说明是一个空文件 // 初始化值 try { Properties p = new Properties(); p.put("driver", driver); p.put("url", url); p.put("user", user); p.put("password", password); FileOutputStream fos = new FileOutputStream(file); p.store(fos, "配置文件信息"); fos.close(); } catch (IOException e) { e.printStackTrace(); } } else {// 如果有值 // 将信息读取出来 try { FileInputStream fis = new FileInputStream(file); Properties p = new Properties(); p.load(fis); this.driver = p.getProperty("driver"); this.url = p.getProperty("url"); this.user = p.getProperty("user"); this.password = p.getProperty("password"); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } // 建立连接 private void initConnect() { try { Class.forName(driver); this.connect = DriverManager.getConnection(url, user, password); this.connect.setAutoCommit(false);// 设置手动提交事务 this.stmt = connect.createStatement(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } /*/ 从tomcat缓冲池获取连接 private void initConnectFromDataSource() { try { InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/oracleds"); this.connect = ds.getConnection(); this.connect.setAutoCommit(false); this.stmt = connect.createStatement(); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }*/ // 需要调用者控制事务的两个方法 // 提交方法 private void commit() { try { this.connect.commit(); } catch (SQLException e) { e.printStackTrace(); } } // 回滚事务 private void rollBack() { try { this.connect.rollback(); } catch (SQLException e) { e.printStackTrace(); } } // 定义一组与操作有关的方法 // 使用普通通道执行的select public ResultSet select(String sql) { ResultSet prs = null; if (stmt != null) { try { prs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } } return prs; } // 根据传入的sql直接获取单一值 // 使用此方法的时候sql语句返回的单一的值 public String selectFirstValue(String sql, String type, List<String> csList) { String rstr = ""; rs = select(sql, type, csList);// 确定此结果集只有一条记录 if (rs != null) {// 说明结果集有值,且只有一条记录 try { ResultSetMetaData rsmd = rs.getMetaData(); if (rs.next()) { // 移动到第一条记录 String p_type = rsmd.getColumnTypeName(1); rstr = getResultSetValue(rs, 1, p_type); } } catch (SQLException e) { e.printStackTrace(); } } return rstr; } // 使用普通通道执行的select /** * sql 参数 type 使用通道的类型 stmt pstmt cstmt List<String> csList 预编通道执行的参数队列 * String 最少必须满足如下条件的字符串 数据类型 ,数据值 数据类型定义说明 字符串 数字(整数、小数) 日期(DATE、TIMESTAMP) */ public ResultSet select(String sql, String type, List<String> csList) { ResultSet prs = null; if (type.equals(stmtType)) {// 说明使用普通通道来执行 prs = select(sql); } else if (type.equals(pstmtType)) {// 说明使用预编译通道来执行 if (connect != null) { try { pstmt = connect.prepareStatement(sql); // 验证传入的参数和sql中的参数个数一致 setPrepareStatement(pstmt, csList);// 将参数设置进当前的预编译通道 prs = pstmt.executeQuery(); } catch (Exception e) { e.printStackTrace(); } } } return prs; } // 获取 总页数 public int getPageNumber(String sql, String type, List<String> csList, int pageSize) { // 处理总页数 int pageNumber = 0; // 第一步获取sql总记录数 String psql = "select count(*) from (" + sql + ")"; String result = selectFirstValue(psql, type, csList); int rows = 0; if (result != null && result.trim() != "") { rows = Integer.valueOf(result); } if (rows % pageSize == 0) { pageNumber = rows / pageSize; } else { pageNumber = rows / pageSize + 1; } return pageNumber; } /** * 自动添加分页查询方法 * * @param sql * 要执行的sql * @param type * 执行方式 * @param csList * 参数列表 * @param curPage * 当前页数 * @param pageSize * 每页记录数 默认为10 * @return */ public ResultSet selectByFY(String sql, String type, List<String> csList, int curPage, int pageSize) { ResultSet prs = null; // 处理 每页记录数 if (pageSize <= 0) { pageSize = 10;// 默认页面10条记录 } int pageNumber = getPageNumber(sql, type, csList, pageSize); // 处理当前页数 if (curPage < 0) { curPage = 1;// 默认第一页 } if (curPage > pageNumber) { curPage = pageNumber; } String psql = "select tmpaa.* from (select tmpa.*,(select (ROW_NUMBER() over (order by id))) as rn from (" + sql + ") tmpa where (select (ROW_NUMBER() over (order by id))) <= " + (curPage * pageSize) + ") tmpaa where tmpaa.rn >= " + ((curPage - 1) * pageSize + 1); prs = select(psql, type, csList); return prs; } // 将预编通道执行的参数队列按照指定规则设置进通道中 private void setPrepareStatement(PreparedStatement p, List<String> csList) throws Exception { if (csList != null && csList.size() > 0) { for (int i = 0; i < csList.size(); i++) { // 此处的str是数据类型 ,数据值 // 解析出数据类型和数据值 String[] s = csList.get(i).split(","); String sType = s[0]; String sData = s[1]; if (varCharType.equals(sType)) { p.setString(i + 1, sData); } else if (intType.equals(sType)) { p.setInt(i + 1, Integer.valueOf(sData)); } else if(doubleType.equals(sType)){ p.setDouble(i+1, Double.valueOf(sData)); } else if (dateType.equals(sType)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); java.util.Date d = sdf.parse(sData); p.setDate(i + 1, new Date(d.getTime())); } else if (timeType.equals(sType)) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); java.util.Date d = sdf.parse(sData); p.setTimestamp(i + 1, new Timestamp(d.getTime())); } } } } // 定义一个执行insert update delete的方法 public int iudSql(String sql) { int ri = -1; if (stmt != null) { try { ri = stmt.executeUpdate(sql); commit(); } catch (SQLException e) { e.printStackTrace(); rollBack(); } } return ri; } public int iudSql(String sql, String type, List<String> csList) { int ri = -1; if (stmtType.equals(type)) { ri = iudSql(sql); } else if (pstmtType.equals(type)) { if (connect != null) { try { pstmt = connect.prepareStatement(sql); setPrepareStatement(pstmt, csList); ri = pstmt.executeUpdate(); commit(); } catch (Exception e) { e.printStackTrace(); rollBack(); } } } return ri; } /** * 编写一个通用的遍历ResultSet结果集的方法 */ public void iteratorResultSet(ResultSet rs) { try { if (rs != null) {// 说明有值 // ResultSetMetaData 此对象里封装了与结果集有关所有信息 // 此结果有几列组成,每列的列名,每列的数据类型 ResultSetMetaData rsmd = rs.getMetaData(); // 得到结果集列数 int columnCount = rsmd.getColumnCount(); // 输出此结果集的所有列名 for (int i = 1; i <= columnCount; i++) { System.out.print(rsmd.getColumnName(i) + "\t"); } System.out.println(""); // 遍历输出所有的数据 while (rs.next()) { // 如何在获取rs中的数据? for (int i = 1; i <= columnCount; i++) { String type = rsmd.getColumnTypeName(i); System.out.print(getResultSetValue(rs, i, type) + "\t"); } System.out.println(""); } } } catch (SQLException e) { e.printStackTrace(); } } // 从ResultSet中根据数据类型来得到数据值的方法 // 先处理常用的sqlserver的数据类型的对应 private String getResultSetValue(ResultSet rs, int index, String type) { String rstr = ""; try { if (rs != null && !"".equals(type) && index > 0) { if ("char".equals(type.trim()) || "varchar".equals(type.trim())) { if (rs.getString(index) != null) { rstr = rs.getString(index); } } else if ("int".equals(type.trim())) { rstr = rs.getInt(index) + ""; } else if ("decimal".equals(type.trim())) { rstr = String.valueOf(rs.getDouble(index)); } else if ("date".equals(type.trim())) { Date date = rs.getDate(index); if (date != null) { rstr = new SimpleDateFormat("yyyy年MM月dd日").format(date); } } else if ("timestamp".equals(type.trim()) || "datetime".equals(type.trim())) { Timestamp tt = rs.getTimestamp(index); if (tt != null) { rstr = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(tt); } } } } catch (SQLException e) { e.printStackTrace(); } return rstr; } /* //统一事务管理的批量sql的封装 public boolean iudSql(List<String> sqlList){ int ri = -1; if(stmt!=null){ try { ri = stmt.executeUpdate(sql); commit(); } catch (SQLException e) { e.printStackTrace(); rollBack(); } } return ri; }*/ // 关闭连接 public void close() { try { // 关闭所有的与数据库有关的对象 if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (pstmt != null) { pstmt.close(); pstmt = null; } if (cstmt != null) { cstmt.close(); cstmt = null; } if (connect != null) { connect.close(); connect = null; } } catch (SQLException e) { e.printStackTrace(); } } }
dao包的组织
公司转向java、有一个疑问不解 1 把erp中所有项目的dao(包括select insert update)放在一个包下、如果这样结构就不是很清晰、看起来比较乱、不知效率如何? 2 每一个项目的dao放在各自的包中、如果这样applicationContext.xml中就得为每个项目配置datasource、事务 请问你们实际中开发中是怎样做的?各有何利弊?
java多线程高并发下的oracle数据库异常
代码的功能是生成一个随机的序列化的订单号,正常的情况下一个一个跑没问题,在进行压力测试的时候,多线程高并发下,oracle的create语句就会报错,说是 java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sqlSQLException: ORA-00955: 名称已由现有对象使用 求大神看下。 代码如下: ``` package utils.spring; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import utils.Lang; import javax.sql.DataSource; import java.sql.*; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 序列发生器(可用于高并发、可回收等场景) * * @author lujijiang * */ @Component @ConfigurationProperties(prefix = "seqGenerator") final public class SequenceGenerator implements InitializingBean { interface Atom<T> { T atom(Connection connection) throws Exception; } public static <T> T atom(Connection connection, Atom<T> atom) throws Exception { connection.setAutoCommit(false); connection .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); try { T obj = atom.atom(connection); connection.commit(); return obj; } catch (Exception e) { connection.rollback(); throw e; } } static Map<String, String> createSqlMap = new ConcurrentHashMap<String, String>(); static { createSqlMap .put("h2", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("mysql", "CREATE TABLE %s (v$key BIGINT NOT NULL,v$key$ varchar(256),v$seq BIGINT NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("informix", "CREATE TABLE %s (v$key DECIMAL(16,0) NOT NULL,v$key$ varchar(256),v$seq DECIMAL(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); createSqlMap .put("oracle", "CREATE TABLE %s (v$key NUMBER(16,0) NOT NULL,v$key$ varchar2(256),v$seq NUMBER(16,0) NOT NULL,v$state CHAR(1) NOT NULL, PRIMARY KEY (v$key,v$seq))"); } static Map<String, String> insertSqlMap = new ConcurrentHashMap<String, String>(); static { insertSqlMap .put("h2", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("mysql", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select ifnull(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("informix", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); insertSqlMap .put("oracle", "insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',(select nvl(max(t.v$seq),%d)+%d from %s t where t.v$key=%d),'1')"); } /** * 事务模版 */ TransactionTemplate transactionTemplate; /** * 是否使用新事务 */ boolean newTransaction = true; /** * JDBC模版 */ JdbcTemplate jdbcTemplate; /** * 尝试次数(默认10次) */ int tryTime = 10; /** * 数据库类型 */ String databaseType; /** * 表名 */ private String tableName; /** * 容量 */ private int capacity = 25; /** * 步进 */ private int step = 1; /** * 是否可回收序列号 */ protected boolean recyclable; @Autowired public void setTransactionManager( PlatformTransactionManager transactionManager) { if (transactionManager != null) { transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate .setIsolationLevel(TransactionTemplate.ISOLATION_READ_COMMITTED); transactionTemplate .setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED); } } public boolean isNewTransaction() { return newTransaction; } public void setNewTransaction(boolean newTransaction) { this.newTransaction = newTransaction; } public TransactionTemplate getTransactionTemplate() { return transactionTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setDataSource(DataSource dataSource) { if (jdbcTemplate == null) { jdbcTemplate = new JdbcTemplate(dataSource); } } public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } public void setTryTime(int tryTime) { this.tryTime = tryTime; } public void setDatabaseType(String databaseType) { if (databaseType != null) { databaseType = databaseType.trim().toLowerCase(); this.databaseType = databaseType; } } public void setTableName(String tableName) { this.tableName = tableName == null ? null : tableName.trim(); } public void setCapacity(int capacity) { this.capacity = capacity; } public void setStep(int step) { this.step = step < 1 ? 1 : step; } public void setRecyclable(boolean recyclable) { this.recyclable = recyclable; } /** * 创建序列 * * @param name * @param length * @param start * @return */ public String generateSequence(String name, int length, long start) { final long key = generateKey(name); try { return generateSequence(key, length, start, name); } catch (Throwable t) { createSequenceTable();//错误就是定位在这里 int time = tryTime >= 0 ? tryTime : 10000; while (time-- > 0) { try { return generateSequence(key, length, start, name); } catch (Throwable e) { } } throw new RuntimeException("Generate sequence failure", t); } } private long generateKey(String name) { return 10000000000L + name.trim().hashCode(); } /** * 创建序列 * * @param key * @param length * @return */ public String generateSequence(String key, int length) { return generateSequence(key, length, 0); } /** * 创建序列 * * @param key * @return */ public String generateSequence(String key) { return generateSequence(key, 6); } private synchronized void createSequenceTable() { try { jdbcTemplate.execute(new ConnectionCallback<Integer>() { public Integer doInConnection(Connection connection) throws SQLException, DataAccessException { ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null); try { while (rs.next()) { return 1; } } finally { rs.close(); } String createSql = String.format( createSqlMap.get(databaseType), tableName); Statement statement = connection.createStatement(); try { statement.execute(createSql);//错误就是定位在这里 } finally { statement.close(); } return 0; } }); } catch (Throwable t) { throw new RuntimeException(t); } } private String generateSequence(final long key, final int length, final long start, final String name) { if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { return atom(connection, new Atom<String>() { @Override public String atom(Connection connection) throws Exception { if (recyclable) { String no = getRecoveredSequence(connection, key, length); if (no != null) { return no; } } Statement statement = connection.createStatement(); try { String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { Long max = rs.getLong(1); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(connection, deleteSql); insertSql = String.format( insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(connection, insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(connection, deleteSql); } return fillLeftZero(max, length); } } finally { rs.close(); } } finally { statement.close(); } throw new IllegalStateException( SequenceGenerator.this.getClass() .getSimpleName() + "无法获取单号,不可能发生的异常"); } }); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } return getTransactionTemplate().execute( new TransactionCallback<String>() { public String doInTransaction(TransactionStatus ts) { try { if (recyclable) { String no = jdbcTemplate .execute(new ConnectionCallback<String>() { public String doInConnection( Connection connection) throws SQLException, DataAccessException { return getRecoveredSequence( connection, key, length); } }); if (no != null) { return no; } } String insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name .replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); String querySql = String .format("select max(v$seq) from %s where v$key=%d and v$state='1'", tableName, key); Long max = jdbcTemplate.queryForObject(querySql, Long.class); if (max < start) {// 重新初始化 String deleteSql = String .format("delete from %s where v$key=%d and v$state='1'", tableName, key); execute(deleteSql); insertSql = String.format(insertSqlMap .get(databaseType), tableName, key, name.replace("'", "''"), start < 0 ? 0 : start, step, tableName, key); execute(insertSql); return fillLeftZero(start, length); } if (capacity > 0 && max % capacity == 0) { String deleteSql = String .format("delete from %s where v$key=%d and v$seq<>%d and v$state='1'", tableName, key, max); execute(deleteSql); } return fillLeftZero(max, length); } catch (Throwable t) { ts.isRollbackOnly(); throw new RuntimeException(t); } } }); } /** * 参数化执行SQL * * @param sql * @param args * @return */ protected int execute(String sql, final Object... args) { return jdbcTemplate.execute(sql, new PreparedStatementCallback<Integer>() { public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } }); } /** * 参数化执行SQL * * @param sql * @param args * @return * @throws SQLException */ protected int execute(Connection conn, String sql, final Object... args) throws SQLException { PreparedStatement ps = conn.prepareStatement(sql); try { if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject(i + 1, args[i]); } } return ps.executeUpdate(); } finally { ps.close(); } } protected String fillLeftZero(Long max, int length) { StringBuilder sb = new StringBuilder(); sb.append(max); if (sb.length() >= length) { return sb.substring(sb.length() - length); } else { for (int i = sb.length(); i < length; i++) { sb.insert(0, '0'); } } return sb.toString(); } /** * 获取已回收的序列 * * @param connection * @param key * @throws SQLException */ protected String getRecoveredSequence(Connection connection, long key, int length) throws SQLException { Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); try { String querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' for update", tableName, key); statement.executeQuery(querySql); querySql = String .format("select v$key,v$seq,v$state from %s where v$key = %d and v$state<>'1' order by v$seq asc", tableName, key); ResultSet rs = statement.executeQuery(querySql); try { while (rs.next()) { try { Long min = rs.getLong(2); rs.updateString(3, "1"); rs.updateRow(); return fillLeftZero(min, length); } catch (Throwable ex) { } } } finally { rs.close(); } } finally { statement.close(); } return null; } /** * 回收序列号 * * @param name * @param sequence */ public void recoveredSequence(final String name, final String sequence) { final long key = generateKey(name); final long seq = Long.valueOf(sequence); if (newTransaction) { try { Connection connection = jdbcTemplate.getDataSource() .getConnection(); try { atom(connection, new Atom<Object>() { public Object atom(Connection connection) throws Exception { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(connection, updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(connection, insertSql); } return null; } }); connection.commit(); } finally { connection.close(); } } catch (Exception e) { throw Lang.unchecked(e); } } else { transactionTemplate.execute(new TransactionCallback<Integer>() { public Integer doInTransaction(TransactionStatus status) { try { String updateSql = String .format("update %s set v$state='0' where v$key=%d and v$seq=%d", tableName, key, seq); int count = execute(updateSql); if (count == 0) { String insertSql = String .format("insert into %s(v$key,v$key$,v$seq,v$state) values(%d,'%s',%d,'0')", tableName, key, name.replace("'", "''"), seq); execute(insertSql); } return null; } catch (Throwable t) { status.isRollbackOnly(); throw new RuntimeException(t); } } }); } } public void afterPropertiesSet() throws Exception { if (this.databaseType == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "databaseType")); } if (databaseType != null) { if (!createSqlMap.containsKey(databaseType)) { throw new IllegalStateException(String.format( "Unsupported database type:%s", databaseType)); } } if (this.jdbcTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' or '%s' is required", "dataSource", "jdbcTemplate")); } if (this.tableName == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "tableName")); } if (!tableName.matches("[a-zA-Z_][a-zA-Z0-9_]*") || tableName.length() > 16) { throw new IllegalStateException(String.format( "Illegal tableName:%s", tableName)); } if (!this.newTransaction) { if (this.transactionTemplate == null) { throw new IllegalArgumentException(String.format( "Property '%s' is required", "transactionManager")); } } } } ``` java.lang.RuntimeException: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:272) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:202) at utils.spring.SequenceGenerator.generateSequence(SequenceGenerator.java:227) at cart.service.service.OrderService.generateOrderNo(OrderService.java:806) at cart.service.service.OrderService.saveVirtualGoodsToOrder(OrderService.java:220) at cart.service.service.OrderService$$FastClassBySpringCGLIB$$19f99be7.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) 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.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) at cart.service.service.OrderService$$EnhancerBySpringCGLIB$$feb8eef.saveVirtualGoodsToOrder(<generated>) at cart.service.apiImpl.OrderMainApiImpl.saveVirtualGoodsToOrder(OrderMainApiImpl.java:223) at cart.service.apiImpl.OrderMainApiImpl$$FastClassBySpringCGLIB$$fa3518e.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) at cart.service.apiImpl.OrderMainApiImpl$$EnhancerBySpringCGLIB$$497f044.saveVirtualGoodsToOrder(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.weibo.api.motan.rpc.DefaultProvider.invoke(DefaultProvider.java:57) at com.weibo.api.motan.rpc.AbstractProvider.call(AbstractProvider.java:47) at com.weibo.api.motan.filter.AccessLogFilter.filter(AccessLogFilter.java:56) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at utils.rpc.motan.filter.OpenEntityManagerInMotanFilter.filter(OpenEntityManagerInMotanFilter.java:171) at com.weibo.api.motan.protocol.support.ProtocolFilterDecorator$2.call(ProtocolFilterDecorator.java:150) at com.weibo.api.motan.transport.ProviderMessageRouter.call(ProviderMessageRouter.java:96) at com.weibo.api.motan.transport.ProviderProtectedMessageRouter.call(ProviderProtectedMessageRouter.java:79) at com.weibo.api.motan.transport.ProviderMessageRouter.handle(ProviderMessageRouter.java:91) at com.weibo.api.motan.transport.support.DefaultRpcHeartbeatFactory$HeartMessageHandleWrapper.handle(DefaultRpcHeartbeatFactory.java:82) at com.weibo.api.motan.transport.netty.NettyChannelHandler.processRequest(NettyChannelHandler.java:139) at com.weibo.api.motan.transport.netty.NettyChannelHandler.access$000(NettyChannelHandler.java:47) at com.weibo.api.motan.transport.netty.NettyChannelHandler$1.run(NettyChannelHandler.java:116) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.jdbc.BadSqlGrammarException: ConnectionCallback; bad SQL grammar []; nested exception is java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:360) at utils.spring.SequenceGenerator.createSequenceTable(SequenceGenerator.java:247) ... 39 more Caused by: java.sql.SQLException: ORA-00955: 名称已由现有对象使用 at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288) at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745) at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:210) at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:961) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1190) at oracle.jdbc.driver.OracleStatement.executeInternal(OracleStatement.java:1726) at oracle.jdbc.driver.OracleStatement.execute(OracleStatement.java:1696) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:264) at utils.spring.SequenceGenerator$1.doInConnection(SequenceGenerator.java:247) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:353) ... 40 more
Mybatis小练习 报错 求大神指导,信息详尽
# UserMapper ``` public interface UserMapper { //根据id查询用户信息 public User findUserById(int id) throws Exception; //根据用户名列查询用户列表 public List<User> findUserByName(String name)throws Exception; //插入用户 public void insertUser(User user)throws Exception; } ``` # UserMapper.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离 注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace等于mapper接口地址 --> <mapper namespace="com.neuedu.mapper.UserMapper"> <!-- 在 映射文件中配置很多sql语句 --> <!-- 需求:通过id查询用户表的记录 --> <!-- 通过 select执行数据库查询 id:标识 映射文件中的 sql 将sql语句封装到mappedStatement对象中,所以将id称为statement的id parameterType:指定输入 参数的类型,这里指定int型 #{}表示一个占位符号 #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称 resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。 --> <select id="findUserById" parameterType="int" resultType="user"> SELECT * FROM user WHERE id=#{value} </select> <!-- 根据用户名称模糊查询用户信息,可能返回多条 resultType:指定就是单条记录所映射的java对象 类型 ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中。 使用${}拼接sql,引起 sql注入 ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value --> <select id="findUserByName" parameterType="java.lang.String" resultType="com.neuedu.pojo.User"> SELECT * FROM user WHERE username LIKE '%${value}%' </select> <!-- 添加用户 parameterType:指定输入 参数类型是pojo(包括 用户信息) #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值 --> <insert id="insertUser" parameterType="com.neuedu.pojo.User"> <!-- 将插入数据的主键返回,返回到user对象中 SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键 keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性 order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序 resultType:指定SELECT LAST_INSERT_ID()的结果类型 --> insert into user(id,username,birthday,sex,address) values (seq_user.nextval,#{username},#{birthday},#{sex},#{address}) <!-- 插入数据后,返回自动增长列的ID值,将sql语句的返回值赋给parameterType绑定对象的ID属性 MySQL中使用: select LAST_INSERT_ID() --> <selectKey keyProperty="id" order="AFTER" resultType="int"> SELECT LAST_INSERT_ID() <!--select seq_user.currval from dual--> </selectKey> <!-- 使用mysql的uuid()生成主键 执行过程: 首先通过uuid()得到主键,将主键设置到user对象的id属性中 其次在insert执行时,从user对象中取出id属性值 --> <!-- <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String"> SELECT uuid() </selectKey> insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) --> </insert> <!-- 删除 用户 根据id删除用户,需要输入 id值 --> <delete id="deleteUser" parameterType="java.lang.Integer"> delete from user where id=#{id} </delete> <!-- 根据id更新用户 分析: 需要传入用户的id 需要传入用户的更新信息 parameterType指定user对象,包括 id和更新信息,注意:id必须存在 #{id}:从输入 user对象中获取id属性值 --> <update id="updateUser" parameterType="com.neuedu.pojo.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> </mapper> ``` # Tset ``` public class UserMapperTest { private SqlSessionFactory sqlSessionFactory; // 此方法是在执行testFindUserById之前执行 @Before public void setUp() throws Exception { // 创建sqlSessionFactory // mybatis配置文件 String resource = "config/SqlMapConfig.xml"; // 得到配置文件流 InputStream inputStream = Resources.getResourceAsStream(resource); // 创建会话工厂,传入mybatis的配置文件信息 sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); } @Test public void testFindUserById() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); //创建UserMapper对象,mybatis自动生成mapper代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //调用userMapper的方法 User user = userMapper.findUserById(1); System.out.println(user); } @Test public void testFindUserByName() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); //创建UserMapper对象,mybatis自动生成mapper代理对象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //调用userMapper的方法 List<User> list = userMapper.findUserByName("袁超"); sqlSession.close(); System.out.println(list); } } ``` # 报错信息 ``` DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. DEBUG [main] - Class not found: org.jboss.vfs.VFS DEBUG [main] - JBoss 6 VFS API is not available in this environment. DEBUG [main] - Class not found: org.jboss.vfs.VirtualFile DEBUG [main] - VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment. DEBUG [main] - Using VFS adapter org.apache.ibatis.io.DefaultVFS DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo DEBUG [main] - Reader entry: User.class DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo/User.class DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/pojo/User.class DEBUG [main] - Reader entry: ���� 1 N DEBUG [main] - Checking to see if class com.neuedu.pojo.User matches criteria [is assignable to Object] DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - PooledDataSource forcefully closed/removed all connections. DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper DEBUG [main] - Reader entry: UserMapperTest.class DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper/UserMapperTest.class DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/test-classes/com/neuedu/mapper/UserMapperTest.class DEBUG [main] - Reader entry: ���� 1 a DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper DEBUG [main] - Reader entry: UserMapper.class DEBUG [main] - Reader entry: UserMapper.xml DEBUG [main] - Listing file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.class DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.class DEBUG [main] - Reader entry: ���� 1    findUserById (I)Lcom/neuedu/pojo/User; DEBUG [main] - Find JAR URL: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.xml DEBUG [main] - Not a JAR: file:/C:/Users/95638/Desktop/mybatis/ch02-mybatis01/ch02-mybatis01/target/classes/com/neuedu/mapper/UserMapper.xml DEBUG [main] - Reader entry: <?xml version="1.0" encoding="UTF-8" ?> DEBUG [main] - Checking to see if class com.neuedu.mapper.UserMapperTest matches criteria [is assignable to Object] DEBUG [main] - Checking to see if class com.neuedu.mapper.UserMapper matches criteria [is assignable to Object] DEBUG [main] - Opening JDBC Connection DEBUG [main] - Created connection 209833425. DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@c81cdd1] DEBUG [main] - ==> Preparing: SELECT * FROM T_USER WHERE username LIKE '%袁超%' DEBUG [main] - ==> Parameters: org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist ### The error may exist in com/neuedu/mapper/UserMapper.xml ### The error may involve com.neuedu.mapper.UserMapper.findUserByName-Inline ### The error occurred while setting parameters ### SQL: SELECT * FROM T_USER WHERE username LIKE '%袁超%' ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59) at com.sun.proxy.$Proxy3.findUserByName(Unknown Source) at com.neuedu.mapper.UserMapperTest.testFindUserByName(UserMapperTest.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mybatis.t_user' doesn't exist at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.jdbc.Util.handleNewInstance(Util.java:400) at com.mysql.jdbc.Util.getInstance(Util.java:383) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901) at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1193) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59) at com.sun.proxy.$Proxy5.execute(Unknown Source) at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63) at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) ... 29 more ``` # SqlMapConfig.xml ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 加载属性文件 --> <properties resource="db.properties"> <!--properties中还可以配置一些属性名和属性值 --> <!-- <property name="jdbc.driver" value=""/> --> </properties> <!-- 全局配置参数,需要时再设置 --> <!-- <settings> </settings> --> <!-- 别名定义 --> <typeAliases> <!-- 针对单个别名定义 type:类型的路径 alias:别名 --> <!-- <typeAlias type="com.neuedu.mybatis.po.User" alias="user"/> --> <!-- 批量别名定义 指定包名,mybatis自动扫描包中的po类,自动定义别名,别名就是类名(首字母大写或小写都可以) --> <package name="com.neuedu.pojo"/> </typeAliases> <!-- 和spring整合后 environments配置将废除--> <environments default="development"> <environment id="development"> <!-- 使用jdbc事务管理,事务控制由mybatis--> <transactionManager type="JDBC" /> <!-- 数据库连接池,由mybatis管理--> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <!-- 加载 映射文件 --> <mappers> <mapper resource="sqlmap/User.xml"/> <!--通过resource方法一次加载一个映射文件 --> <!-- <mapper resource="sqlmap/User.xml"/> --> <!-- 通过mapper接口加载单个 映射文件 遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中 上边规范的前提是:使用的是mapper代理方法 --> <!-- <mapper class="com.neuedu.mapper.UserMapper"/> --> <!-- 批量加载mapper 指定mapper接口的包名,mybatis自动扫描包下边所有mapper接口进行加载 遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录 中 上边规范的前提是:使用的是mapper代理方法 --> <package name="com.neuedu.mapper"/> </mappers> </configuration> ``` # User ``` public class User { //属性名和数据库表的字段对应 private int id; private String username;// 用户姓名 private String sex;// 性别 private Date birthday;// 生日 private String address;// 地址 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } } ``` 也不知道为什么,明明已经在UserMapper.xml里面把表名改了,但是报错信息里查找的还是T-user表 求大神指导!感恩! # 问题已解决 在maven文件里加上下面的代码 ``` <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*Mapper.xml</include> </includes> </resource> </resources> ```
JDBC事务难题
大牛们 ,,,有一段加了JDBC事务的方法 [code="java"] public boolean updateStuAcc(int stuID, List accL, int schID) { boolean b = true; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql1 = "select * from stuAccounts where stuID!=? and Account=?"; String sql2 = "update stuAccounts set Account=? where pactID=?"; String sql3 = "update [" + schID + "_StuRefundInfo] set account=? where pactID=? "; try { conn = DBCon.getCon(); conn.setAutoCommit(false); for (int i = 0; i < accL.size(); i++) { StuUpdateAccDto suaDto = (StuUpdateAccDto) accL.get(i); ps = conn.prepareStatement(sql1); ps.setInt(1, stuID); ps.setString(2, suaDto.getAccount()); rs = ps.executeQuery(); if (rs.next()) { b = false; break; } else { ps = conn.prepareStatement(sql2); ps.setString(1, suaDto.getAccount()); ps.setString(2, suaDto.getPactID()); ps.executeUpdate(); ps = conn.prepareStatement(sql3); ps.setString(1, suaDto.getAccount()); ps.setString(2, suaDto.getPactID()); ps.execute(); } } conn.commit(); } catch (SQLException e) { b = false; try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return b; } [/code] 该方法有时候会抛出这样的异常 at java.lang.Thread.run(Thread.java:595) com.microsoft.sqlserver.jdbc.SQLServerException: 事务(进程 ID 54)与另一个进程被 死锁在 锁 资源上,并且已被选作死锁牺牲品。请重新运行该事务。 at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError (Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePrep aredStatement(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecC md.doExecute(Unknown Source) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unkno wn Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknow n Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unkn own Source) at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery( Unknown Source) at org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement.executeQuery( DelegatingPreparedStatement.java:93) at dao.StuAllInfoUDao.updateStuAcc(StuAllInfoUDao.java:33) at workerServlet.SchUpdateStuInfoServlet.doPost(SchUpdateStuInfoServlet. java:59) 请问是什么原因????
学生成绩管理系统添加班级模块错误,下面是数据库的操作代码和控制台的代码,还有错误提示,求帮忙
//添加班级 public void addClass(int pid,String className) { String sql="insert into class (pid,classname) values(?,?)"; Connection connection=null; PreparedStatement p=null; try { connection=DbUtil.getConnection(); //手动提交事务 connection.setAutoCommit(false); p=(PreparedStatement) connection.prepareStatement(sql); p.setInt(1, pid); p.setString(2, className); p.executeUpdate(); //获取当前班级的父班级 Classes parentClass=findClassById(pid); //如果父班级为叶子 if (parentClass.getLeaf()==1) { modLeaf(connection, parentClass.getClassId(), 0); } //提交事务 connection.commit(); } catch (Exception e) { e.printStackTrace(); if (connection!=null) { try { connection.rollback(); } catch (Exception e1) { e1.printStackTrace(); } } } finally { DbUtil.colse(p); //恢复成自动提交 DbUtil.setAutoCommit(connection, true); DbUtil.colse(connection); } } /** * 修改叶子值如果为叶子 * @throws SQLException */ private void modLeaf(Connection connection,int classId,int leaf) throws SQLException{ String sql="update class set leaf=? where classid=?"; PreparedStatement p=null; try { p=(PreparedStatement) connection.prepareStatement(sql); p.setInt(1, leaf); p.setInt(2, classId); p.executeUpdate(); } finally { DbUtil.colse(p); } } /** * 根据ID查找班级 * 查询父班级是否为叶子 * 如果存在返回班级,不存在返回空 * @return */ public Classes findClassById(int classId) { String sql="select *form class where classid=?" ; Connection connection=null; PreparedStatement p=null; ResultSet rs=null; Classes classes=null; try { connection=DbUtil.getConnection(); p=(PreparedStatement) connection.prepareStatement(sql); rs=(ResultSet) p.executeQuery(); if(rs.next()) { classes=new Classes(); classes.setClassId(classId); classes.setClassName(rs.getString("classname")); classes.setPid(rs.getInt("pid")); classes.setLeaf(rs.getInt("leaf")); } } catch (Exception e) { e.printStackTrace(); } finally { DbUtil.colse(rs); DbUtil.colse(p); DbUtil.colse(connection); } return classes; } } 控制台代码,应该没错,s为输出的添加信息 int pid=Integer.parseInt(s.substring(s.indexOf("=")+1, s.indexOf(","))); String className=s.substring(s.lastIndexOf("=")+1, s.length()); ClassManage.getInstance().addClass(pid, className); 错误信息: 1-添加班级 2-删除班级 3-修改班级 4-查询班级 q-退出 1 请输入添加的班级名(classname=#): pid=3,classname=一年一班_01 java.sql.SQLException: Field 'leaf' doesn't have a default value at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723) at com.mysql.jdbc.Connection.execSQL(Connection.java:3256) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1313) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1585) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1500) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1485) at com.coursemanage.lsq.ClassManage.addClass(ClassManage.java:67) at com.coursecontroller.lsq.ClassController.main(ClassController.java:47)
求大神帮忙 spring aop 方式事务不回滚怎么搞?
spring 版本 4.1.7 代码如下: 表: CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `nick_name` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; INSERT INTO `users` VALUES ('1', 'Jennifer', 'Alice'); INSERT INTO `users` VALUES ('2', '爱', '克斯莱'); java 文件: 1) package com.maxwell.spring.jdbc.tx; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.maxwell.spring.jdbc.vo.User; @Service public class UserAopService { @Autowired private UserDao dao; public UserAopService() {} /** * 此处的@Transactional注解把这个方法中的所有数据库操作当作事务进行处理 */ public void testTransactionManager() { String nn = dao.addUser(new User().setNickName("Jensen").setPassword("jensen")); int i = dao.getIdByNickName(nn); System.out.println(i); dao.setNickNameById(i, "Nimei"); } } 2) package com.maxwell.spring.jdbc.tx; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import com.maxwell.spring.jdbc.vo.User; /** * 用于测试事务 * @author Techwork * */ @Repository public class UserDao { @Autowired @Qualifier("npJdbcTpl") private NamedParameterJdbcTemplate jdbcTpl; public String addUser(User user) { String sql = "INSERT INTO users (nick_name, password) VALUES (:nickName, :password)"; SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user); jdbcTpl.update(sql, paramSource); return user.getNickName(); } public int getIdByNickName(String nickName) { String sql = "select id, nick_name, password from users where nick_name = :xxx"; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("xxx", nickName); RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class); List<User> users = jdbcTpl.query(sql, paramMap, rowMapper); if(users == null || users.size() < 1) { throw new RuntimeException("无此用户:" + nickName); } return users.get(0).getId(); } public void setNickNameById(int id, String nickName) { if(nickName.length() < 10) throw new RuntimeException("性别错误"); String sql = "update users set nick_name = :n where id = :i"; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("n", nickName); paramMap.put("i", id); jdbcTpl.update(sql, paramMap); } } 3) package com.maxwell.spring.jdbc.tx; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.maxwell.spring.jdbc.vo.User; @Service public class UserService { @Autowired private UserDao dao; public UserService() {} /** * 此处的@Transactional注解把这个方法中的所有数据库操作当作事务进行处理 */ @Transactional public void testTransactionManager() { String nn = dao.addUser(new User().setNickName("Jensen").setPassword("jensen")); int i = dao.getIdByNickName(nn); System.out.println(i); dao.setNickNameById(i, "Nimei"); } /** * propagation: 指定事务的传播行为 * isolation: 指定事务的隔离级别 * noRollbackFor: 指定对哪些异常不回滚。通常取默认值。 * rollbackFor: 指定对哪些异常回滚。通常取默认值。 * readOnly: 只读事务。如果事务只读取数据,而不写数据的话,设置为true,有助于数据库引擎优化事务。 * timeout: 指定强制回滚事务(就算可能成功)之前,事务可以存在的时间,以防止事务占用数据库连接时间过长。 */ @Transactional(isolation = Isolation.READ_COMMITTED, noRollbackFor = { Exception.class }, rollbackFor = { RuntimeException.class }, readOnly = true, timeout = 3) public void testTransactionManager2() { String nn = dao.addUser(new User().setNickName("Jensen").setPassword("jensen")); int i = dao.getIdByNickName(nn); dao.setNickNameById(i, "哈哈"); } } 4) package com.maxwell.spring.jdbc; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.maxwell.spring.jdbc.tx.UserAopService; /** * 测试AOP事务 * * @author Angrynut * */ public class AOPTransactionTest { private ApplicationContext ctx = null; private UserAopService service = null; { ctx = new ClassPathXmlApplicationContext("aoptx.xml"); service = ctx.getBean("userAopService", UserAopService.class); } /** * 1.测试AOP事务。 */ @Test public void testTransactionManager() { service.testTransactionManager(); } } 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:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"> <context:component-scan base-package="com.maxwell.spring.jdbc"/> <!-- 数据源配置文件 --> <util:properties id="db" location="classpath:db.properties"/> <!-- 配置C3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="#{db['jdbc.user']}"/> <property name="password" value="#{db['jdbc.password']}"/> <property name="driverClass" value="#{db['jdbc.driverClass']}"/> <property name="jdbcUrl" value="#{db['jdbc.jdbcUrl']}"/> <property name="initialPoolSize" value="#{db['jdbc.initPoolSize']}"/> <property name="maxPoolSize" value="#{db['jdbc.maxPoolSize']}"/> </bean> <bean id="npJdbcTpl" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.maxwell.spring.jdbc.tx.UserService.*(..))" id="pc"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/> </aop:config> </beans>
为什么我配置Spring的事务后不能得到BEAN
我配置Spring的事务后不能得到BEAN 如果把事务的部分去掉的话就能够得到 下面这是applicationContext.xml [code="xml"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd "> <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"></property> <property name="url" value="jdbc:jtds:sqlserver://localhost:1433/soft2005"></property> <property name="username" value="sa"></property> <property name="password" value=""></property> </bean> <bean id="SessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"></property> <property name="mappingResources"> <list> <value>com/yhwj/secsms/po/Cgnx.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SybaseDialect </prop> </props> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="SessionFactory"></property> </bean> <tx:advice id="myadvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> <aop:config> <!-- <aop:pointcut id="myPoin" expression="execution(* com.yhwj.secsms.dao.CgnxDAO.*(..))"/> <aop:advisor id="myAdvi" advice-ref="myadvice" pointcut-ref="myPoin"/> --> <aop:advisor pointcut="execution(* com.yhwj.secsms.dao.CgnxDAO.*(..))" advice-ref="myadvice"/> </aop:config> <bean id="CgnxDAO" class="com.yhwj.secsms.dao.CgnxDAO"> <property name="sessionFactory"> <ref bean="SessionFactory" /> </property> </bean></beans> [/code] 下面是测试类cgnxTest.java [code="java"] package com.yhwj.secsms.bo; import java.util.Iterator; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.yhwj.secsms.dao.CgnxDAO; import com.yhwj.secsms.po.Cgnx; import junit.framework.TestCase; public class cgnxTest extends TestCase { ApplicationContext ac=new FileSystemXmlApplicationContext("src/applicationContext.xml"); public void testCgnxAddFind() { CgnxDAO cdao=(CgnxDAO) ac.getBean("CgnxDAO"); com.yhwj.secsms.vo.Cgnx cg=new com.yhwj.secsms.vo.Cgnx(); cg.setCgnx("12年"); Cgnx cg1=(Cgnx) cg.getPO(); cdao.save(cg1); List l=cdao.findAll(); assertTrue(l.size()>0); } } [/code] 下面的是运行后LOG4J抓的东西 INFO - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3: display name [org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3]; startup date [Wed Jul 02 09:09:49 CST 2008]; root of context hierarchy DEBUG - Class [org.apache.commons.collections.map.LinkedMap] or one of its dependencies is not present: java.lang.ClassNotFoundException: org.apache.commons.collections.map.LinkedMap DEBUG - Creating [java.util.concurrent.ConcurrentHashMap] DEBUG - Creating [java.util.LinkedHashSet] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Creating [java.util.LinkedHashSet] DEBUG - Creating [java.util.concurrent.ConcurrentHashMap] DEBUG - Creating [java.util.concurrent.ConcurrentHashMap] DEBUG - Loading schema mappings from [META-INF/spring.schemas] DEBUG - Loaded schema mappings: {http://www.springframework.org/schema/aop/spring-aop-2.0.xsd=org/springframework/aop/config/spring-aop-2.0.xsd, http://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd, http://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd, http://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd, http://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd, http://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd, http://www.springframework.org/schema/aop/spring-aop.xsd=org/springframework/aop/config/spring-aop-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd, http://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd, http://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd} DEBUG - Loading schema mappings from [META-INF/spring.schemas] DEBUG - Loaded schema mappings: {http://www.springframework.org/schema/aop/spring-aop-2.0.xsd=org/springframework/aop/config/spring-aop-2.0.xsd, http://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd, http://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd, http://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd, http://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd, http://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd, http://www.springframework.org/schema/aop/spring-aop.xsd=org/springframework/aop/config/spring-aop-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd, http://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd, http://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd} INFO - Loading XML bean definitions from file [F:\自助设备客户服务管理系统\工程\src\applicationContext.xml] DEBUG - Using JAXP provider [org.apache.xerces.jaxp.DocumentBuilderFactoryImpl] DEBUG - Trying to resolve XML entity with public id [null] and system id [http://www.springframework.org/schema/beans/spring-beans-2.0.xsd] DEBUG - Found XML schema [http://www.springframework.org/schema/beans/spring-beans-2.0.xsd] in classpath: org/springframework/beans/factory/xml/spring-beans-2.0.xsd DEBUG - Trying to resolve XML entity with public id [null] and system id [http://www.springframework.org/schema/tx/spring-tx-2.0.xsd] DEBUG - Found XML schema [http://www.springframework.org/schema/tx/spring-tx-2.0.xsd] in classpath: org/springframework/transaction/config/spring-tx-2.0.xsd DEBUG - Trying to resolve XML entity with public id [null] and system id [http://www.springframework.org/schema/aop/spring-aop-2.0.xsd] DEBUG - Found XML schema [http://www.springframework.org/schema/aop/spring-aop-2.0.xsd] in classpath: org/springframework/aop/config/spring-aop-2.0.xsd DEBUG - Loaded mappings [{http://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler, http://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler, http://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler, http://www.springframework.org/schema/aop=org.springframework.aop.config.AopNamespaceHandler, http://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler, http://www.springframework.org/schema/tx=org.springframework.transaction.config.TxNamespaceHandler}] DEBUG - Loading bean definitions DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Loaded 8 bean definitions from location pattern [src/applicationContext.xml] INFO - Bean factory for application context [org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3]: org.springframework.beans.factory.support.DefaultListableBeanFactory@16c9867 DEBUG - 8 beans defined in org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3: display name [org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3]; startup date [Wed Jul 02 09:09:49 CST 2008]; root of context hierarchy DEBUG - Creating shared instance of singleton bean 'org.springframework.aop.config.internalAutoProxyCreator' DEBUG - Creating instance of bean 'org.springframework.aop.config.internalAutoProxyCreator' with merged definition [Root bean: class [org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] DEBUG - Getting BeanInfo for class [org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator] DEBUG - Caching PropertyDescriptors for class [org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator] DEBUG - Found bean property 'advisorAdapterRegistry' of type [org.springframework.aop.framework.adapter.AdvisorAdapterRegistry] DEBUG - Found bean property 'applyCommonInterceptorsFirst' of type [boolean] DEBUG - Found bean property 'beanClassLoader' of type [java.lang.ClassLoader] DEBUG - Found bean property 'beanFactory' of type [org.springframework.beans.factory.BeanFactory] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'customTargetSourceCreators' of type [[Lorg.springframework.aop.framework.autoproxy.TargetSourceCreator;] DEBUG - Found bean property 'exposeProxy' of type [boolean] DEBUG - Found bean property 'frozen' of type [boolean] DEBUG - Found bean property 'interceptorNames' of type [[Ljava.lang.String;] DEBUG - Found bean property 'opaque' of type [boolean] DEBUG - Found bean property 'optimize' of type [boolean] DEBUG - Found bean property 'order' of type [int] DEBUG - Found bean property 'proxyTargetClass' of type [boolean] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Eagerly caching bean 'org.springframework.aop.config.internalAutoProxyCreator' to allow for resolving potential circular references INFO - Bean 'org.springframework.aop.config.internalAutoProxyCreator' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) DEBUG - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@148662] DEBUG - Creating [java.util.LinkedHashSet] DEBUG - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@178460d] DEBUG - Creating [java.util.LinkedHashMap] INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@16c9867: defining beans [myDataSource,SessionFactory,txManager,myadvice,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJExpressionPointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor,CgnxDAO]; root of factory hierarchy DEBUG - Creating shared instance of singleton bean 'myDataSource' DEBUG - Creating instance of bean 'myDataSource' with merged definition [Root bean: class [org.springframework.jdbc.datasource.DriverManagerDataSource]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [F:\自助设备客户服务管理系统\工程\src\applicationContext.xml]] DEBUG - Getting BeanInfo for class [org.springframework.jdbc.datasource.DriverManagerDataSource] DEBUG - Caching PropertyDescriptors for class [org.springframework.jdbc.datasource.DriverManagerDataSource] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'connection' of type [java.sql.Connection] DEBUG - Found bean property 'connectionProperties' of type [java.util.Properties] DEBUG - Found bean property 'driverClassName' of type [java.lang.String] DEBUG - Found bean property 'logWriter' of type [java.io.PrintWriter] DEBUG - Found bean property 'loginTimeout' of type [int] DEBUG - Found bean property 'password' of type [java.lang.String] DEBUG - Found bean property 'url' of type [java.lang.String] DEBUG - Found bean property 'username' of type [java.lang.String] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Eagerly caching bean 'myDataSource' to allow for resolving potential circular references INFO - Loaded JDBC driver: net.sourceforge.jtds.jdbc.Driver DEBUG - Creating shared instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' DEBUG - Creating instance of bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' with merged definition [Root bean: class [org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] DEBUG - Did not attempt to auto-proxy infrastructure class [org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor] DEBUG - Getting BeanInfo for class [org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor] DEBUG - Caching PropertyDescriptors for class [org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor] DEBUG - Found bean property 'advice' of type [org.aopalliance.aop.Advice] DEBUG - Found bean property 'adviceBeanName' of type [java.lang.String] DEBUG - Found bean property 'beanFactory' of type [org.springframework.beans.factory.BeanFactory] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'order' of type [int] DEBUG - Found bean property 'perInstance' of type [boolean] DEBUG - Found bean property 'pointcut' of type [org.springframework.aop.Pointcut] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Eagerly caching bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' to allow for resolving potential circular references DEBUG - Creating instance of bean 'org.springframework.aop.aspectj.AspectJExpressionPointcut' with merged definition [Root bean: class [org.springframework.aop.aspectj.AspectJExpressionPointcut]; scope=prototype; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] DEBUG - Getting BeanInfo for class [org.springframework.aop.aspectj.AspectJExpressionPointcut] DEBUG - Caching PropertyDescriptors for class [org.springframework.aop.aspectj.AspectJExpressionPointcut] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'classFilter' of type [org.springframework.aop.ClassFilter] DEBUG - Found bean property 'expression' of type [java.lang.String] DEBUG - Found bean property 'location' of type [java.lang.String] DEBUG - Found bean property 'methodMatcher' of type [org.springframework.aop.MethodMatcher] DEBUG - Found bean property 'parameterNames' of type [[Ljava.lang.String;] DEBUG - Found bean property 'parameterTypes' of type [[Ljava.lang.Class;] DEBUG - Found bean property 'pointcutDeclarationScope' of type [java.lang.Class] DEBUG - Found bean property 'pointcutExpression' of type [org.aspectj.weaver.tools.PointcutExpression] DEBUG - Found bean property 'runtime' of type [boolean] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Creating [java.util.LinkedHashSet] DEBUG - Creating shared instance of singleton bean 'SessionFactory' DEBUG - Creating instance of bean 'SessionFactory' with merged definition [Root bean: class [org.springframework.orm.hibernate3.LocalSessionFactoryBean]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [F:\自助设备客户服务管理系统\工程\src\applicationContext.xml]] DEBUG - Getting BeanInfo for class [org.springframework.orm.hibernate3.LocalSessionFactoryBean] DEBUG - Caching PropertyDescriptors for class [org.springframework.orm.hibernate3.LocalSessionFactoryBean] DEBUG - Found bean property 'cacheableMappingLocations' of type [[Lorg.springframework.core.io.Resource;] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'collectionCacheStrategies' of type [java.util.Properties] DEBUG - Found bean property 'configLocation' of type [org.springframework.core.io.Resource] DEBUG - Found bean property 'configLocations' of type [[Lorg.springframework.core.io.Resource;] DEBUG - Found bean property 'configuration' of type [org.hibernate.cfg.Configuration] DEBUG - Found bean property 'configurationClass' of type [java.lang.Class] DEBUG - Found bean property 'dataSource' of type [javax.sql.DataSource] DEBUG - Found bean property 'entityCacheStrategies' of type [java.util.Properties] DEBUG - Found bean property 'entityInterceptor' of type [org.hibernate.Interceptor] DEBUG - Found bean property 'eventListeners' of type [java.util.Map] DEBUG - Found bean property 'exposeTransactionAwareSessionFactory' of type [boolean] DEBUG - Found bean property 'filterDefinitions' of type [[Lorg.hibernate.engine.FilterDefinition;] DEBUG - Found bean property 'hibernateProperties' of type [java.util.Properties] DEBUG - Found bean property 'jdbcExceptionTranslator' of type [org.springframework.jdbc.support.SQLExceptionTranslator] DEBUG - Found bean property 'jtaTransactionManager' of type [javax.transaction.TransactionManager] DEBUG - Found bean property 'lobHandler' of type [org.springframework.jdbc.support.lob.LobHandler] DEBUG - Found bean property 'mappingDirectoryLocations' of type [[Lorg.springframework.core.io.Resource;] DEBUG - Found bean property 'mappingJarLocations' of type [[Lorg.springframework.core.io.Resource;] DEBUG - Found bean property 'mappingLocations' of type [[Lorg.springframework.core.io.Resource;] DEBUG - Found bean property 'mappingResources' of type [[Ljava.lang.String;] DEBUG - Found bean property 'namingStrategy' of type [org.hibernate.cfg.NamingStrategy] DEBUG - Found bean property 'object' of type [java.lang.Object] DEBUG - Found bean property 'objectType' of type [java.lang.Class] DEBUG - Found bean property 'schemaUpdate' of type [boolean] DEBUG - Found bean property 'singleton' of type [boolean] DEBUG - Found bean property 'typeDefinitions' of type [[Lorg.springframework.orm.hibernate3.TypeDefinitionBean;] DEBUG - Found bean property 'useTransactionAwareDataSource' of type [boolean] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Eagerly caching bean 'SessionFactory' to allow for resolving potential circular references DEBUG - Returning cached instance of singleton bean 'myDataSource' DEBUG - Creating [java.util.LinkedHashSet] DEBUG - Creating [java.util.LinkedHashMap] INFO - Hibernate 3.1.3 INFO - hibernate.properties not found INFO - using CGLIB reflection optimizer INFO - using JDK 1.4 java.sql.Timestamp handling DEBUG - trying to resolve system-id [http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd] DEBUG - recognized hibernate namespace; attempting to resolve on classpath under org/hibernate/ DEBUG - located [http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd] in classpath INFO - Mapping class: com.yhwj.secsms.po.Cgnx -> cgnx DEBUG - Mapped property: cgnxId -> cgnxID DEBUG - Mapped property: cgnx -> cgnx INFO - Building new Hibernate SessionFactory DEBUG - Preparing to build session factory with filters : {} DEBUG - processing extends queue DEBUG - processing collection mappings DEBUG - processing native query and ResultSetMapping mappings DEBUG - processing association property references DEBUG - processing foreign key constraints INFO - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider DEBUG - Creating new JDBC Connection to [jdbc:jtds:sqlserver://localhost:1433/soft2005] INFO - RDBMS: Microsoft SQL Server, version: 08.00.2039 INFO - JDBC driver: jTDS Type 4 JDBC Driver for MS SQL Server and Sybase, version: 1.2.2 INFO - Using dialect: org.hibernate.dialect.SybaseDialect INFO - Using default transaction strategy (direct JDBC transactions) INFO - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) INFO - Automatic flush during beforeCompletion(): disabled INFO - Automatic session close at end of transaction: disabled INFO - Scrollable result sets: enabled DEBUG - Wrap result sets: disabled INFO - JDBC3 getGeneratedKeys(): enabled INFO - Connection release mode: on_close INFO - Default batch fetch size: 1 INFO - Generate SQL with comments: disabled INFO - Order SQL updates by primary key: disabled INFO - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory INFO - Using ASTQueryTranslatorFactory INFO - Query language substitutions: {} INFO - Second-level cache: enabled INFO - Query cache: disabled INFO - Cache provider: org.hibernate.cache.EhCacheProvider INFO - Optimize cache for minimal puts: disabled INFO - Structured second-level cache entries: disabled DEBUG - Using dialect defined converter INFO - Statistics: disabled INFO - Deleted entity synthetic identifier rollback: disabled INFO - Default entity-mode: pojo INFO - building session factory DEBUG - Session factory constructed with filter configurations : {} DEBUG - instantiating session factory with properties: {java.runtime.name=Java(TM) 2 Runtime Environment, Standard Edition, sun.boot.library.path=D:\Program Files\MyEclipse 5.5 GA\jre\bin, java.vm.version=1.5.0_11-b03, java.vm.vendor=Sun Microsystems Inc., java.vendor.url=http://java.sun.com/, path.separator=;, java.vm.name=Java HotSpot(TM) Client VM, file.encoding.pkg=sun.io, user.country=CN, sun.java.launcher=SUN_STANDARD, sun.os.patch.level=Service Pack 3, java.vm.specification.name=Java Virtual Machine Specification, user.dir=F:\自助设备客户服务管理系统\工程, java.runtime.version=1.5.0_11-b03, java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment, java.endorsed.dirs=D:\Program Files\MyEclipse 5.5 GA\jre\lib\endorsed, os.arch=x86, java.io.tmpdir=C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\, line.separator= , java.vm.specification.vendor=Sun Microsystems Inc., user.variant=, os.name=Windows XP, sun.jnu.encoding=GBK, java.library.path=D:\Program Files\MyEclipse 5.5 GA\jre\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Java\jdk1.5.0_07\\bin;C:\Program Files\Microsoft SQL Server\80\Tools\BINN;C:\Program Files\StormII\Codec;C:\Program Files\StormII, java.specification.name=Java Platform API Specification, java.class.version=49.0, sun.management.compiler=HotSpot Client Compiler, os.version=5.1, user.home=C:\Documents and Settings\Administrator, user.timezone=Asia/Shanghai, hibernate.connection.release_mode=on_close, java.awt.printerjob=sun.awt.windows.WPrinterJob, file.encoding=GBK, java.specification.version=1.5, java.class.path=F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\classes;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jstl.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\standard.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\antlr-2.7.6rc1.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\asm-attrs.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\asm.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\c3p0-0.9.0.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\cglib-2.1.3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commons-collections-2.1.1.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commons-logging-1.0.4.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\concurrent-1.3.2.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\connector.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\dom4j-1.6.1.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\ehcache-1.1.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\hibernate3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jaas.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jacc-1_0-fr.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jaxen-1.1-beta-7.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jboss-cache.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jboss-common.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jboss-jmx.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jboss-system.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jdbc2_0-stdext.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jgroups-2.2.8.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jta.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jtds-1.2.2.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\log4j-1.2.11.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\oscache-2.1.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\proxool-0.8.3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\swarmcache-1.0rc2.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\xerces-2.6.2.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\xml-apis.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\aopalliance.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\asm-2.2.3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\asm-commons-2.2.3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\asm-util-2.2.3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\aspectjrt.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\aspectjweaver.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\backport-util-concurrent.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\bsh-2.0b4.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\c3p0-0.9.1.1.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\cglib-nodep-2.1_3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commonj-twm.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commons-attributes-api.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commons-attributes-compiler.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commons-dbcp.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commons-lang.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\commons-logging.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\ehcache-1.2.4.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\groovy-1.0.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\hessian-3.0.20.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\hibernate-annotations.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\hibernate-commons-annotations.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\hibernate-entitymanager.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\ibatis-2.3.0.677.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jakarta-oro-2.0.8.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jamon-2.4.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jboss-archive-browsing.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jdo2-api.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jmxremote.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jmxremote_optional.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jmxri.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jotm.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\jruby.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\log4j-1.2.14.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\openjpa-0.9.7-incubating.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\persistence.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\quartz-all-1.6.0.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\serp-1.12.1.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-agent.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-aop.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-beans.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-context.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-core.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-dao.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-hibernate3.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-ibatis.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-jdbc.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-jdo.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-jmx.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-jpa.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-remoting.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-support.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-tomcat-weaver.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\spring-toplink.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\toplink-api.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\toplink-essentials.jar;F:\自助设备客户服务管理系统\工程\WebRoot\WEB-INF\lib\xapool.jar;D:\Program Files\MyEclipse 5.5 GA\eclipse\plugins\org.junit_3.8.1\junit.jar;/D:/Program Files/MyEclipse 5.5 GA/eclipse/plugins/org.eclipse.jdt.junit_3.2.1.r321_v20060810/junitsupport.jar;/D:/Program Files/MyEclipse 5.5 GA/eclipse/plugins/org.eclipse.jdt.junit.runtime_3.2.1.r321_v20060721/junitruntime.jar, user.name=Administrator, java.vm.specification.version=1.0, sun.arch.data.model=32, java.home=D:\Program Files\MyEclipse 5.5 GA\jre, hibernate.dialect=org.hibernate.dialect.SybaseDialect, java.specification.vendor=Sun Microsystems Inc., user.language=zh, awt.toolkit=sun.awt.windows.WToolkit, java.vm.info=mixed mode, hibernate.cglib.use_reflection_optimizer=true, java.version=1.5.0_11, java.ext.dirs=D:\Program Files\MyEclipse 5.5 GA\jre\lib\ext, sun.boot.class.path=D:\Program Files\MyEclipse 5.5 GA\jre\lib\rt.jar;D:\Program Files\MyEclipse 5.5 GA\jre\lib\i18n.jar;D:\Program Files\MyEclipse 5.5 GA\jre\lib\sunrsasign.jar;D:\Program Files\MyEclipse 5.5 GA\jre\lib\jsse.jar;D:\Program Files\MyEclipse 5.5 GA\jre\lib\jce.jar;D:\Program Files\MyEclipse 5.5 GA\jre\lib\charsets.jar;D:\Program Files\MyEclipse 5.5 GA\jre\classes;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\activation.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\javax.servlet.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\javax.servlet.jsp.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\jboss-j2ee.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\jboss-jaxrpc.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\jboss-jsr77.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\jboss-saaj.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\mail.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\namespace.jar;D:\Program Files\MyEclipse 5.5 GA\myeclipse\eclipse\plugins\com.genuitec.eclipse.j2eedt.core_5.5.0\data\libraryset\1.4\xml-apis.jar, java.vendor=Sun Microsystems Inc., file.separator=\, java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport.cgi, hibernate.connection.provider_class=org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider, sun.cpu.endian=little, sun.io.unicode.encoding=UnicodeLittle, sun.desktop=windows, sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86} DEBUG - Creating new CacheManager with default config DEBUG - Configuring ehcache from classpath. WARN - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/F:/%e8%87%aa%e5%8a%a9%e8%ae%be%e5%a4%87%e5%ae%a2%e6%88%b7%e6%9c%8d%e5%8a%a1%e7%ae%a1%e7%90%86%e7%b3%bb%e7%bb%9f/%e5%b7%a5%e7%a8%8b/WebRoot/WEB-INF/lib/ehcache-1.1.jar!/ehcache-failsafe.xml DEBUG - Disk Store Path: C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ DEBUG - Static SQL for entity: com.yhwj.secsms.po.Cgnx DEBUG - Version select: select cgnxID from secsms.dbo.cgnx where cgnxID =? DEBUG - Snapshot select: select cgnx_.cgnxID, cgnx_.cgnx as cgnx0_ from secsms.dbo.cgnx cgnx_ where cgnx_.cgnxID=? DEBUG - Insert 0: insert into secsms.dbo.cgnx (cgnx, cgnxID) values (?, ?) DEBUG - Update 0: update secsms.dbo.cgnx set cgnx=? where cgnxID=? DEBUG - Delete 0: delete from secsms.dbo.cgnx where cgnxID=? DEBUG - Identity insert: insert into secsms.dbo.cgnx (cgnx) values (?) DEBUG - Static select for entity com.yhwj.secsms.po.Cgnx: select cgnx0_.cgnxID as cgnxID0_0_, cgnx0_.cgnx as cgnx0_0_ from secsms.dbo.cgnx cgnx0_ where cgnx0_.cgnxID=? DEBUG - Static select for entity com.yhwj.secsms.po.Cgnx: select cgnx0_.cgnxID as cgnxID0_0_, cgnx0_.cgnx as cgnx0_0_ from secsms.dbo.cgnx cgnx0_ where cgnx0_.cgnxID=? DEBUG - Static select for entity com.yhwj.secsms.po.Cgnx: select cgnx0_.cgnxID as cgnxID0_0_, cgnx0_.cgnx as cgnx0_0_ from secsms.dbo.cgnx cgnx0_ where cgnx0_.cgnxID=? DEBUG - Static select for entity com.yhwj.secsms.po.Cgnx: select cgnx0_.cgnxID as cgnxID0_0_, cgnx0_.cgnx as cgnx0_0_ from secsms.dbo.cgnx cgnx0_ where cgnx0_.cgnxID=? DEBUG - Static select for action ACTION_MERGE on entity com.yhwj.secsms.po.Cgnx: select cgnx0_.cgnxID as cgnxID0_0_, cgnx0_.cgnx as cgnx0_0_ from secsms.dbo.cgnx cgnx0_ where cgnx0_.cgnxID=? DEBUG - Static select for action ACTION_REFRESH on entity com.yhwj.secsms.po.Cgnx: select cgnx0_.cgnxID as cgnxID0_0_, cgnx0_.cgnx as cgnx0_0_ from secsms.dbo.cgnx cgnx0_ where cgnx0_.cgnxID=? DEBUG - initializing class SessionFactoryObjectFactory DEBUG - registered: 4028808b1ae151ae011ae151b9410000 (unnamed) INFO - Not binding factory to JNDI, no JNDI name configured DEBUG - instantiated session factory DEBUG - Checking 0 named HQL queries DEBUG - Checking 0 named SQL queries DEBUG - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' DEBUG - Creating shared instance of singleton bean 'txManager' DEBUG - Creating instance of bean 'txManager' with merged definition [Root bean: class [org.springframework.orm.hibernate3.HibernateTransactionManager]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [F:\自助设备客户服务管理系统\工程\src\applicationContext.xml]] DEBUG - Getting BeanInfo for class [org.springframework.orm.hibernate3.HibernateTransactionManager] DEBUG - Caching PropertyDescriptors for class [org.springframework.orm.hibernate3.HibernateTransactionManager] DEBUG - Found bean property 'autodetectDataSource' of type [boolean] DEBUG - Found bean property 'beanFactory' of type [org.springframework.beans.factory.BeanFactory] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'dataSource' of type [javax.sql.DataSource] DEBUG - Found bean property 'defaultTimeout' of type [int] DEBUG - Found bean property 'entityInterceptor' of type [org.hibernate.Interceptor] DEBUG - Found bean property 'entityInterceptorBeanName' of type [java.lang.String] DEBUG - Found bean property 'failEarlyOnGlobalRollbackOnly' of type [boolean] DEBUG - Found bean property 'globalRollbackOnParticipationFailure' of type [boolean] DEBUG - Found bean property 'jdbcExceptionTranslator' of type [org.springframework.jdbc.support.SQLExceptionTranslator] DEBUG - Found bean property 'nestedTransactionAllowed' of type [boolean] DEBUG - Found bean property 'prepareConnection' of type [boolean] DEBUG - Found bean property 'resourceFactory' of type [java.lang.Object] DEBUG - Found bean property 'rollbackOnCommitFailure' of type [boolean] DEBUG - Found bean property 'sessionFactory' of type [org.hibernate.SessionFactory] DEBUG - Found bean property 'transactionSynchronization' of type [int] DEBUG - Found bean property 'transactionSynchronizationName' of type [java.lang.String] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Eagerly caching bean 'txManager' to allow for resolving potential circular references DEBUG - Returning cached instance of singleton bean 'SessionFactory' DEBUG - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' DEBUG - Creating [java.util.LinkedHashSet] INFO - Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@76db09] of Hibernate SessionFactory for HibernateTransactionManager DEBUG - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' DEBUG - Creating shared instance of singleton bean 'myadvice' DEBUG - Creating instance of bean 'myadvice' with merged definition [Root bean: class [org.springframework.transaction.interceptor.TransactionInterceptor]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] DEBUG - Did not attempt to auto-proxy infrastructure class [org.springframework.transaction.interceptor.TransactionInterceptor] DEBUG - Getting BeanInfo for class [org.springframework.transaction.interceptor.TransactionInterceptor] DEBUG - Caching PropertyDescriptors for class [org.springframework.transaction.interceptor.TransactionInterceptor] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'transactionAttributeSource' of type [org.springframework.transaction.interceptor.TransactionAttributeSource] DEBUG - Found bean property 'transactionAttributeSources' of type [[Lorg.springframework.transaction.interceptor.TransactionAttributeSource;] DEBUG - Found bean property 'transactionAttributes' of type [java.util.Properties] DEBUG - Found bean property 'transactionManager' of type [org.springframework.transaction.PlatformTransactionManager] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Eagerly caching bean 'myadvice' to allow for resolving potential circular references DEBUG - Returning cached instance of singleton bean 'txManager' DEBUG - Creating [java.util.LinkedHashSet] DEBUG - Creating instance of bean '(inner bean)' with merged definition [Root bean: class [org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] DEBUG - Getting BeanInfo for class [org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource] DEBUG - Caching PropertyDescriptors for class [org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'nameMap' of type [java.util.Map] DEBUG - Found bean property 'properties' of type [java.util.Properties] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Adding transactional method [*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT] DEBUG - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' DEBUG - Creating [java.util.LinkedHashSet] DEBUG - Creating shared instance of singleton bean 'CgnxDAO' DEBUG - Creating instance of bean 'CgnxDAO' with merged definition [Root bean: class [com.yhwj.secsms.dao.CgnxDAO]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [F:\自助设备客户服务管理系统\工程\src\applicationContext.xml]] DEBUG - Getting BeanInfo for class [com.yhwj.secsms.dao.CgnxDAO] DEBUG - Caching PropertyDescriptors for class [com.yhwj.secsms.dao.CgnxDAO] DEBUG - Found bean property 'class' of type [java.lang.Class] DEBUG - Found bean property 'hibernateTemplate' of type [org.springframework.orm.hibernate3.HibernateTemplate] DEBUG - Found bean property 'sessionFactory' of type [org.hibernate.SessionFactory] DEBUG - Creating [java.util.LinkedHashMap] DEBUG - Eagerly caching bean 'CgnxDAO' to allow for resolving potential circular references DEBUG - Returning cached instance of singleton bean 'SessionFactory' DEBUG - Returning cached instance of singleton bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor' DEBUG - Returning cached instance of singleton bean 'myadvice' DEBUG - Creating [java.util.IdentityHashMap] DEBUG - Creating implicit proxy for bean 'CgnxDAO' with 0 common interceptors and 1 specific interceptors DEBUG - Creating JDK dynamic proxy: target source is SingletonTargetSource for target object [com.yhwj.secsms.dao.CgnxDAO@19855ed] DEBUG - Publishing event in context [org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3]: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3: display name [org.springframework.context.support.FileSystemXmlApplicationContext@8f4fb3]; startup date [Wed Jul 02 09:09:49 CST 2008]; root of context hierarchy] DEBUG - Returning cached instance of singleton bean 'CgnxDAO'
spring加mybatis的事务配置,我如果不加事务方法是可以执行的,配置了事务没效果
``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://${datasource.cloudx.host}:${datasource.cloudx.port}/${datasource.cloudx.database}?useUnicode=true&amp;characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;allowMultiQueries=true" /> <property name="username" value="${datasource.cloudx.user}" /> <property name="password" value="${datasource.cloudx.password}" /> <property name="initialSize" value="5" /> <property name="maxActive" value="50" /> <property name="maxIdle" value="50" /> <property name="minIdle" value="5" /> <property name="maxWait" value="30000" /> <property name="validationQuery" value="SELECT 1+1" /> <property name="defaultAutoCommit" value="false" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:conf-mybatis/mybatis-base.xml" /> <property name="mapperLocations" value="classpath*:conf-mybatis/mybatis-mapper-*.xml" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="iccardTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="iccardTerm" expression="execution(public * com.cessas.cloudx.service.*.*(..))" /> <aop:advisor pointcut-ref="iccardTerm" advice-ref="iccardTxAdvice" /> </aop:config> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` ```这个是spring_aop的配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <aop:aspectj-autoproxy /> </beans> ```
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
死磕YOLO系列,YOLOv1 的大脑、躯干和手脚
YOLO 是我非常喜欢的目标检测算法,堪称工业级的目标检测,能够达到实时的要求,它帮我解决了许多实际问题。 这就是 YOLO 的目标检测效果。它定位了图像中物体的位置,当然,也能预测物体的类别。 之前我有写博文介绍过它,但是每次重新读它的论文,我都有新的收获,为此我准备写一个系列的文章来详尽分析它。这是第一篇,从它的起始 YOLOv1 讲起。 YOLOv1 的论文地址:https://www.c
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片
简明易理解的@SpringBootApplication注解源码解析(包含面试提问)
欢迎关注文章系列 ,关注我 《提升能力,涨薪可待》 《面试知识,工作可待》 《实战演练,拒绝996》 欢迎关注我博客,原创技术文章第一时间推出 也欢迎关注公 众 号【Ccww笔记】,同时推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《提升能力,涨薪可待篇》- @SpringBootApplication注解源码解析 一、@SpringBootApplication 的作用是什
西游记团队中如果需要裁掉一个人,会先裁掉谁?
2019年互联网寒冬,大批企业开始裁员,下图是网上流传的一张截图: 裁员不可避免,那如何才能做到不管大环境如何变化,自身不受影响呢? 我们先来看一个有意思的故事,如果西游记取经团队需要裁员一名,会裁掉谁呢,为什么? 西游记团队组成: 1.唐僧 作为团队teamleader,有很坚韧的品性和极高的原则性,不达目的不罢休,遇到任何问题,都没有退缩过,又很得上司支持和赏识(直接得到唐太宗的任命,既给
Python语言高频重点汇总
Python语言高频重点汇总 GitHub面试宝典仓库——点这里跳转 文章目录Python语言高频重点汇总**GitHub面试宝典仓库——点这里跳转**1. 函数-传参2. 元类3. @staticmethod和@classmethod两个装饰器4. 类属性和实例属性5. Python的自省6. 列表、集合、字典推导式7. Python中单下划线和双下划线8. 格式化字符串中的%和format9.
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
ES6基础-ES6的扩展
进行对字符串扩展,正则扩展,数值扩展,函数扩展,对象扩展,数组扩展。 开发环境准备: 编辑器(VS Code, Atom,Sublime)或者IDE(Webstorm) 浏览器最新的Chrome 字符串的扩展: 模板字符串,部分新的方法,新的unicode表示和遍历方法: 部分新的字符串方法 padStart,padEnd,repeat,startsWith,endsWith,includes 字
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
你知道的越多,你不知道的越多 点赞再看,养成习惯 本文 GitHub https://github.com/JavaFamily 已收录,有一线大厂面试点思维导图,也整理了很多我的文档,欢迎Star和完善,大家面试可以参照考点复习,希望我们一起有点东西。 前前言 为啥今天有个前前言呢? 因为你们的丙丙啊,昨天有牌面了哟,直接被微信官方推荐,知乎推荐,也就仅仅是还行吧(心里乐开花)
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca
Python爬虫精简步骤1 获取数据
爬虫的工作分为四步: 1.获取数据。爬虫程序会根据我们提供的网址,向服务器发起请求,然后返回数据。 2.解析数据。爬虫程序会把服务器返回的数据解析成我们能读懂的格式。 3.提取数据。爬虫程序再从中提取出我们需要的数据。 4.储存数据。爬虫程序把这些有用的数据保存起来,便于你日后的使用和分析。 这一篇的内容就是:获取数据。 首先,我们将会利用一个强大的库——requests来获取数据。 在电脑上安装
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东
破14亿,Python分析我国存在哪些人口危机!
2020年1月17日,国家统计局发布了2019年国民经济报告,报告中指出我国人口突破14亿。 猪哥的朋友圈被14亿人口刷屏,但是很多人并没有看到我国复杂的人口问题:老龄化、男女比例失衡、生育率下降、人口红利下降等。 今天我们就来分析一下我们国家的人口数据吧! 更多有趣分析教程,扫描下方二维码关注vx公号「裸睡的猪」 即可查看! 一、背景 1.人口突破14亿 2020年1月17日,国家统计局发布
web前端javascript+jquery知识点总结
Javascript javascript 在前端网页中占有非常重要的地位,可以用于验证表单,制作特效等功能,它是一种描述语言,也是一种基于对象(Object)和事件驱动并具有安全性的脚本语言 ,语法同java类似,是一种解释性语言,边执行边解释。 JavaScript的组成: ECMAScipt 用于描述: 语法,变量和数据类型,运算符,逻辑控制语句,关键字保留字,对象。 浏览器对象模型(Br
Qt实践录:开篇
本系列文章介绍笔者的Qt实践之路。 背景 笔者首次接触 Qt 大约是十多年前,当时试用了 Qt ,觉得不如 MFC 好用。现在 Qt 的 API、文档等都比较完善,在年初决定重新拾起,正所谓技多不压身,将 Qt 当为一种谋生工具亦未尝不可。利用春节假期的集中时间,快速专攻一下。 本系列名为“Qt实践”,故不是教程,笔者对 Qt 的定位是“使用”,可以帮助快速编写日常的工具,如串口、网络等。所以不
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ......
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。   再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。   下文是原回答,希望能对你能有所启发。   如果我说,这个世界上人真的分三六九等,
为什么听过很多道理,依然过不好这一生?
记录学习笔记是一个重要的习惯,不希望学习过的东西成为过眼云烟。做总结的同时也是一次复盘思考的过程。 本文是根据阅读得到 App上《万维钢·精英日课》部分文章后所做的一点笔记和思考。学习是一个系统的过程,思维模型的建立需要相对完整的学习和思考过程。以下观点是在碎片化阅读后总结的一点心得总结。
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计
一条链接即可让黑客跟踪你的位置! | Seeker工具使用
搬运自:冰崖的部落阁(icecliffsnet) 严正声明:本文仅限于技术讨论,严禁用于其他用途。 请遵守相对应法律规则,禁止用作违法途径,出事后果自负! 上次写的防社工文章里边提到的gps定位信息(如何防止自己被社工或人肉) 除了主动收集他人位置信息以外,我们还可以进行被动收集 (没有技术含量) Seeker作为一款高精度地理位置跟踪工具,同时也是社交工程学(社会工程学)爱好者...
作为程序员的我,大学四年一直自学,全靠这些实用工具和学习网站!
我本人因为高中沉迷于爱情,导致学业荒废,后来高考,毫无疑问进入了一所普普通通的大学,实在惭愧...... 我又是那么好强,现在学历不行,没办法改变的事情了,所以,进入大学开始,我就下定决心,一定要让自己掌握更多的技能,尤其选择了计算机这个行业,一定要多学习技术。 在进入大学学习不久后,我就认清了一个现实:我这个大学的整体教学质量和学习风气,真的一言难尽,懂的人自然知道怎么回事? 怎么办?我该如何更好的提升
前端JS初级面试题二 (。•ˇ‸ˇ•。)老铁们!快来瞧瞧自己都会了么
1. 传统事件绑定和符合W3C标准的事件绑定有什么区别? 传统事件绑定 &lt;div onclick=""&gt;123&lt;/div&gt; div1.onclick = function(){}; &lt;button onmouseover=""&gt;&lt;/button&gt; 注意: 如果给同一个元素绑定了两次或多次相同类型的事件,那么后面的绑定会覆盖前面的绑定 (不支持DOM事...
Python学习笔记(语法篇)
本篇博客大部分内容摘自埃里克·马瑟斯所著的《Python编程:从入门到实战》(入门类书籍),采用举例的方式进行知识点提要 关于Python学习书籍推荐文章 《学习Python必备的8本书》 Python语法特点: 通过缩进进行语句组织 不需要变量或参数的声明 冒号 1 变量和简单数据结构 1.1 变量命名 只能包含字母、数字和下划线,且不能以数字打头。 1.2 字符串 在Python中,用引号...
[Pyhon疫情大数据分析] 一.腾讯实时数据爬取、Matplotlib和Seaborn可视化分析全国各地区、某省各城市、新增趋势
思来想去,虽然很忙,但还是挤时间针对这次肺炎疫情写个Python大数据分析系列博客,包括网络爬虫、可视化分析、GIS地图显示、情感分析、舆情分析、主题挖掘、威胁情报溯源、知识图谱、预测预警及AI和NLP应用等。第一篇文章将分享腾讯疫情实时数据抓取,获取全国各地和贵州省各地区的实时数据,并将数据存储至本地,最后调用Maplotlib和Seaborn绘制中国各地区、贵州省各城市、新增人数的图形。希望这篇可视化分析文章对您有所帮助!
相关热词 c#如何定义数组列表 c#倒序读取txt文件 java代码生成c# c# tcp发送数据 c#解决时间格式带星期 c#类似hashmap c#设置istbox的值 c#获取多线程返回值 c# 包含数字 枚举 c# timespan
立即提问