前面博客把bean、aop簡單瞭解了一下,今天主要是瞭解Spring中DAO層,若是使用傳統的JDBC時須要建立鏈接、打開、執行sql、關閉鏈接這一系列的步驟,Spring框架對JDBC進行了封裝,咱們只需使用封裝好的JdbcTemplate執行sql語句。主要仍是繼承了Spring提供的JdbcDaoSupport。下面主要是用來演示怎麼使用JdbcDaoSupport。java
1、建立Modelmysql
這裏建立一個User類,做爲model。spring
package Cuiyw.Spring.Model; public class User { private int userId; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; private float money; public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } }
2、建立DAO接口並實現接口sql
1.這裏建立IUserDAO接口,聲明瞭兩個方法,一個是獲取全部的User,一個是新增User。數據庫
package Cuiyw.Spring.IDao; import java.util.*; import Cuiyw.Spring.Model.User; public interface IUserDAO { public List<User>QueryAllUser(); public Boolean AddUser(String name,float money); }
2.這裏實現接口IUserDAO,而且繼承JdbcDaoSupport。在下面的代碼中能找到getJdbcTemplate(),其實咱們右鍵選擇Open declaration 時能夠定位到抽象類JdbcDaoSupport,JdbcDaoSupport裏面有一個JdbcTemplate屬性,並且還有get或set JDBC DataSource,而後選中JdbcTemplate,再Open declaration,發現JdbcTemplate的構造函數須要DataSource,JdbcDaoSupport提供JdbcTemplate對象,並維護着JdbcTemplate對象須要的DataSource。apache
package Cuiyw.Spring.Dao; import java.util.*; import org.springframework.jdbc.core.support.JdbcDaoSupport; import Cuiyw.Spring.IDao.IUserDAO; import Cuiyw.Spring.Model.User; public class UserDAO extends JdbcDaoSupport implements IUserDAO { public List<User> QueryAllUser() { String sql="select id,name,money from tb_user"; List<Map<String,Object>> list=getJdbcTemplate().queryForList(sql); List<User> userList=new ArrayList<User>(); for(Map<String,Object> row:list) { User user=new User(); user.setUserId((Integer)row.get("id")); user.setName((String)row.get("name")); user.setMoney((Float)row.get("money")); userList.add(user); } return userList; } public Boolean AddUser(String name,float money) { String sql="insert into tb_user (name,money) values (?,?)"; int row=getJdbcTemplate().update(sql, new Object[]{name,money}); if(row>0) { return true; } return false; } }
public JdbcTemplate(DataSource dataSource) { setDataSource(dataSource); afterPropertiesSet(); }
3.上下文配置spring-mvc
上面DataSource從哪裏來呢?就須要在上下文中配置。首先配置DataSource,而後因爲UserDAO繼承了抽象類JdbcDaoSupport,因此也須要設置屬性dataSourcemvc
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/spring</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>123456</value> </property> </bean> <bean id="userDao" class="Cuiyw.Spring.Dao.UserDAO" depends-on="dataSource"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
4.Mysql新增數據庫和表框架
上面2中UserDAO執行了兩個sql,涉及到表tb_user,字段id、name、money。在3上下文配置mysql時指定了數據庫名spring。因此按照上面的建立。maven
5.實驗
ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"ApplicationContext.xml"}); BeanFactory factory=context; IUserDAO userDao=(IUserDAO)factory.getBean("userDao"); userDao.AddUser("cuiywA",888); userDao.AddUser("cuiywB",666); List<User> list=userDao.QueryAllUser(); for(User u:list) { System.out.println("name:"+u.getName()+" money: "+u.getMoney()); }
6.錯誤
在實現上面的步驟時報了好幾個錯誤,有由於我疏忽的,還有數據類型和數據庫不一直的,最重要的兩個我這裏也記錄了下來。
1.下面的錯誤是因爲缺乏commons-dbcp.jar、commons-pool.jar致使的
Cannot find class [org.apache.commons.dbcp.BasicDataSource] for bean with name 'dataSource' defined in class path resource [ApplicationContext.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
2.還有就是我在UserDAO中繼承了JdbcDaoSupport,但就是沒自動提示要引入的包,這個第一次沒經驗,百度了才指定須要引入spring-jdbc.jar.
3.忘記引入mysql驅動
Failed to obtain JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'
上面的錯誤都是沒有引入jar包,這裏把pom.xml也放進來,留着之後好用。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Cuiyw</groupId> <artifactId>SpringAop</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringAop</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>5.0.0.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver --> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.4</version> </dependency> <!-- https://mvnrepository.com/artifact/aspectj/aspectjrt --> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.5.4</version> </dependency> </dependencies> </project>