Spring readOnly的简单用法java
在不少时候咱们作一些报表的时候,一个Service方法中不少的查询,可是应用又不仅是只有查询请求,在你执行这些查询期间极可能插入一些数据。例如:spring
//查询 public void selectSomeInfo() throws Exception { ud.selectUserNumbers(); try { // throw new Exception(); Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } ud.selectUserNumbers(); } public void insertInfo() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } ud.insert(9); } public static void main(String args[]) { ApplicationContext ac = new ClassPathXmlApplicationContext( "com/springinaction/springidol/spring-tx.xml"); UserService us = (UserService) ac.getBean("userService"); UserService us1 = (UserService) ac.getBean("userService"); Thread2 t2 = new Thread2(us); Thread1 t1 = new Thread1(us1); t2.start(); t1.start(); //多个线程模拟实际请求 }
查询出来的结果超级容易先后不一致,那咱们应该怎么办呢?Spring 事务管理的 readOnly就能够用来解决这个问题(不过仍是要看是否支持哈,我使用的org.springframework.jdbc.core.JdbcTemplate是支持的)。线程
//修改上文的就能够了 @Transactional( readOnly = true) public void selectSomeInfo() throws Exception { ud.selectUserNumbers(); try { // throw new Exception(); Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } ud.selectUserNumbers(); }
解决这个问题办法其实有不少,但readOnly是 Spring事务管理专门提出来的一个维度,是很是简单使用的。同理上面的传播行为和readOnly实际上是没有比较的理由的。在一些传播行为中其实已经包括了readOnly的做用,二者实际上是处于不一样维度上的东西。均可以解决问题,在保证数据一致上能够从这个维度上很轻松的解决问题而已。
code