寫了個Spring的DAO入門例子。
DAO的接口
1: package dataSourceDemo;
2:
3: public interface IUserDAO {
4: public void insert(User user);
5: public User find(Integer id);
6:
7: }
DAO的實現,必須要有一個setDataSource()的方法,這樣才能出入DataSource。
1: package dataSourceDemo;
2:
3: import java.sql.*;
4:
5: import javax.sql.DataSource;
6:
7: public class UserDAO implements IUserDAO {
8:
9: private DataSource dataSource;
10:
11: public User find(Integer id) {
12: // TODO 自動生成方法存根
13: return null;
14: }
15:
16: public void insert(User user) {
17: // TODO 自動生成方法存根
18: String name = user.getName();
19: int age = user.getAge().intValue();
20:
21: Connection conn = null;
22: Statement stmt =null;
23:
24: try {
25: conn = dataSource.getConnection();
26: stmt = conn.createStatement();
27: String sql = "insert into user (name, age)"+"values('"+name+"',"+age+")";
28: stmt.execute(sql);
29: }catch(Exception e) {
30: e.printStackTrace();
31: } finally {
32: if(stmt != null) {
33: try {
34: stmt.close();
35: }catch(Exception e) {
36: e.printStackTrace();
37: }
38: }
39: if(conn != null) {
40: try {
41: conn.close();
42: } catch(Exception e) {
43: e.printStackTrace();
44: }
45: }
46: }
47: }
48:
49: public DataSource getDataSource() {
50: return dataSource;
51: }
52:
53: public void setDataSource(DataSource dataSource) {
54: this.dataSource = dataSource;
55: }
56:
57: }
USER BEAN
1: package dataSourceDemo;
2:
3: public class User {4: private Integer id;5: private String name;6: private Integer age;7: public Integer getAge() {8: return age;9: }
10: public void setAge(Integer age) {11: this.age = age;12: }
13: public Integer getId() {14: return id;15: }
16: public void setId(Integer id) {17: this.id = id;18: }
19: public String getName() {20: return name;21: }
22: public void setName(String name) {23: this.name = name;24: }
25:
26:
27: }
配置文件,可以很容易的改變dataSource的屬性,就可以輕易改變數據庫的配置:
1: <?xml version="1.0" encoding="UTF-8"?>
2: <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "../resources/spring-beans-2.0.dtd" >
3: <beans>
4: <bean id="dataSource"
5: class="org.springframework.jdbc.datasource.DriverManagerDataSource">
6: <property name="driverClassName">
7: <value>com.mysql.jdbc.Driver</value>
8: </property>
9: <property name="url">
10: <value>jdbc:mysql://localhost:3306/test</value>
11: </property>
12: <property name="username">
13: <value>root</value>
14: </property>
15: <property name="password">
16: <value>123</value>
17: </property>
18: </bean>
19:
20: <bean id="userDAO" class="dataSourceDemo.UserDAO">
21: <property name="dataSource" ref="dataSource"></property>
22: </bean>
23: </beans>
JUNIT測試類
1: package dataSourceDemo;
2:
3: import org.springframework.context.ApplicationContext;
4: import org.springframework.context.support.ClassPathXmlApplicationContext;
5:
6: import junit.framework.TestCase;
7:
8: public class DataSourceTest extends TestCase {
9:
10: private ApplicationContext context;
11:
12: public void setUp() {
13: context = new ClassPathXmlApplicationContext(