<!-- 加載properties文件中 信息 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置數據源 --> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> </bean>
其中,新建 jdbc.properties 文件java
內容:mysql
jdbc.username=root jdbc.password=123456 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/jdbc_template
③在IOC容器中配置JdbcTemplate對象的bean,並將數據源對象裝配到JdbcTemplate對象中spring
<!-- 配置JdbcTemplate對應的bean, 並裝配dataSource數據源屬性--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="comboPooledDataSource"></property> </bean>
@Test public void test() throws SQLException{ ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource bean = ioc.getBean(DataSource.class); System.out.println(bean.getConnection()); }
實驗2:將emp_id=5的記錄的salary字段更新爲1300.00【更新操做】sql
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); private JdbcTemplate bean = ioc.getBean(JdbcTemplate.class); @Test public void test() throws SQLException{ String sql = "UPDATE employee SET salary = ? WHERE emp_id = ?"; bean.update(sql, 1300,5);//第一個是sql語句,後面的按着順序傳入參數便可,這個update方法是接收的可變參數! } }
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); private JdbcTemplate bean = ioc.getBean(JdbcTemplate.class); @Test public void test() throws SQLException{ String sql="INSERT INTO employee(emp_name,salary) VALUES(?,?)"; List<Object[]> list = new ArrayList<Object[]>(); list.add(new Object[]{"Tom2015",1000}); list.add(new Object[]{"Tom2016",2000}); list.add(new Object[]{"Tom2017",3000}); bean.batchUpdate(sql, list); } }
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); private JdbcTemplate bean = ioc.getBean(JdbcTemplate.class); @Test public void test(){ //須要注意的是:sql語句中的別名要與對應實體類的屬性名保持一致! String sql = "SELECT emp_id AS empId,emp_name AS empName,salary FROM employee WHERE emp_id=?"; //RowMapper是一個接口,這裏咱們使用其子類 RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class); //最後一個參數是可變參數,用於向sql語句中依次傳遞參數! Employee employee = bean.queryForObject(sql, rowMapper, 5); System.out.println(employee); } }
實驗5:查詢salary>4000的數據庫記錄,封裝爲List集合返回數據庫
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); private JdbcTemplate bean = ioc.getBean(JdbcTemplate.class); @Test public void test(){ //須要注意的是:sql語句中的別名要與對應實體類的屬性名保持一致! String sql = "SELECT emp_id AS empId,emp_name AS empName,salary FROM employee WHERE salary > ?"; //RowMapper是一個接口,這裏咱們使用其子類 RowMapper<Employee> rowMapper = new BeanPropertyRowMapper<Employee>(Employee.class); //該query方法查詢出來的是一個list列表,query方法的最後一個參數是可變參數! List<Employee> list = bean.query(sql, rowMapper, 4000); for (Employee employee : list) { System.out.println(employee); } } }
實驗6:查詢最大salaryexpress
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); private JdbcTemplate bean = ioc.getBean(JdbcTemplate.class); @Test public void test01(){ String sql = "SELECT MAX(salary) FROM employee"; //須要指定返回值的類型,並且類型必須是包裝類型 Double maxSalary = bean.queryForObject(sql, Double.class); System.out.println(maxSalary); } }
實驗7:使用帶有具名參數的SQL語句插入一條員工記錄,並以Map形式傳入參數值 緩存
<!-- 爲了執行帶有具名參數的SQL語句,須要配置NamedParameterJdbcTemplate --> <!-- 該NamedParameterJdbcTemplate類沒有無參構造器,須要傳入JdbcTemplate對象或者數據源對象[DataSource] --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <!-- 不能使用property標籤配置 --> <constructor-arg ref="jdbcTemplate"></constructor-arg> </bean>
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void test01(){ NamedParameterJdbcTemplate bean2 = ioc.getBean(NamedParameterJdbcTemplate.class); String sql="INSERT INTO employee(emp_name,salary) VALUES(:paramName,:paramSalary)";//具名參數與map 的key 值相同 Map<String,Object> paramMap = new HashMap<String,Object>(); paramMap.put("paramName","張學友" ); paramMap.put("paramSalary",1000); bean2.update(sql, paramMap); } }
實驗8:重複實驗7,以SqlParameterSource形式傳入參數值app
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void test01(){ NamedParameterJdbcTemplate bean2 = ioc.getBean(NamedParameterJdbcTemplate.class); String sql="INSERT INTO employee(emp_name,salary) VALUES(:empName,:salary)"; //該BeanPropertySqlParameterSource類構造器須要一個對象參數,該對象參數是一個封裝了sql語句參數的對象! //此時要求對象的屬性名要和sql中的參數名保持一致!這裏咱們使用Employee對象來完成 Employee employee= new Employee("郭富城", 1500); //以實體對象的形式封裝具名參數和值 SqlParameterSource source = new BeanPropertySqlParameterSource(employee); bean2.update(sql, source); } }
@Repository public class JdbcTemplateDao { @Autowired private JdbcTemplate jdbcTemplate; public void update(){ String sql = "DELETE FROM employee where emp_id = ?"; jdbcTemplate.update(sql, 15); } }
public class TestJDBCTemplate { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); private JdbcTemplate bean = ioc.getBean(JdbcTemplate.class); private JdbcTemplateDao dao = ioc.getBean(JdbcTemplateDao.class); @Test public void testEmployeeDao(){ dao.update(); } }
<context:component-scan base-package="com.neuedu"></context:component-scan> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> </bean> <!-- 以上時JdbcTemplate配置所需 --> <!-- 配置事務管理器 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="comboPooledDataSource"></property> </bean> <!-- 開啓基於註解的聲明式事務 --> <!-- 有時候不須要transaction-manager 由於默認值爲transactionManager --> <!-- 若是事務管理器的id爲transactionManager就不用寫 --> <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
public class TestDataSource { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void test() throws Exception { DataSource bean = ioc.getBean(DataSource.class); System.out.println(bean.getConnection()); } }
@Repository public class BookDao { @Autowired private JdbcTemplate template; public double findPriceByIsbn(String isbn){ String sql = "SELECT price FROM book WHERE isbn = ?"; Double price = template.queryForObject(sql, Double.class, isbn); return price; } public void updateBookStock(String isbn){ String sql="UPDATE book_stock SET stock = stock -1 WHERE isbn = ?"; template.update(sql, isbn); } public void updateAccount(String username,Double price){ String sql = "UPDATE account SET balance = balance - ? WHERE username = ?"; template.update(sql, price,username); } //演示事務的傳播機制 public void updateBookPrice(double price,String isbn){ String sql ="UPDATE book SET price = ? WHERE isbn = ?"; template.update(sql, price,isbn); } }
7.建立 Service 層性能
@Service public class BookService { @Autowired private BookDao bookDao; @Transactional public void doCash(String isbn,String username){ double price = bookDao.findPriceByIsbn(isbn); bookDao.updateBookStock(isbn); try { Thread.sleep(1000*5); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } bookDao.updateAccount(username, price); } @Transactional public void updateBookPrice(double price,String isbn){ bookDao.updateBookPrice(price, isbn); } }
public class TestBookService { private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void test() { BookService bean = ioc.getBean(BookService.class); bean.doCash("ISBN-001", "Tom"); } }
@Transactional(propagation=Propagation.REQUIRED) public void doCash(String isbn,String username){ double price = bookDao.findPriceByIsbn(isbn); bookDao.updateBookStock(isbn); bookDao.updateAccount(username, price); } @Transactional(propagation=Propagation.REQUIRED) public void updateBookPrice(double price,String isbn){ bookDao.updateBookPrice(price, isbn); }
@Transactional(propagation=Propagation.REQUIRES_NEW) public void doCash(String isbn,String username){ double price = bookDao.findPriceByIsbn(isbn); bookDao.updateBookStock(isbn); bookDao.updateAccount(username, price); } @Transactional(propagation=Propagation.REQUIRES_NEW) public void updateBookPrice(double price,String isbn){ bookDao.updateBookPrice(price, isbn); }
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_COMMITTED) public void doCash(String isbn,String username){ double price = bookDao.findPriceByIsbn(isbn); System.out.println(price); bookDao.updateBookStock(isbn); bookDao.updateAccount(username, price); }
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_COMMITTED ,noRollbackFor={ArithmeticException.class} ) public void doCash(String isbn,String username){ double price = bookDao.findPriceByIsbn(isbn); bookDao.updateBookStock(isbn); int i = 10/0;//異常 bookDao.updateAccount(username, price); }
@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_COMMITTED ,noRollbackFor={ArithmeticException.class} ,timeout=3) public void doCash(String isbn,String username){ double price = bookDao.findPriceByIsbn(isbn); bookDao.updateBookStock(isbn); try { Thread.sleep(1000*5); } catch (InterruptedException e) { e.printStackTrace(); } bookDao.updateAccount(username, price); }