为了账号安全,请及时绑定邮箱和手机立即绑定

Spring 数据源配置与应用

标签:
MySQL

Spring 数据源配置与应用

 

Spring对数据库操作都依赖数据源。

Spring有默认的数据源实现org.springframework.jdbc.datasource.DriverManagerDataSource,但也可以配置其他的数据源实现,比如DBCP的数据源public class BasicDataSource  implements javax.sql.DataSource。

 

一旦获取到数据源DataSource实例,就可以通过DataSource获取到数据库连接,操作数据库。

 

下面是Spring数据源的一个简单配置和应用。

应用环境:MySQL5

 

 

drop table if exists user; 

/*==============================================================*/ 

/* Table: user                                                  */ 

/*==============================================================*/ 

create table user 

   id                   bigint AUTO_INCREMENT not null, 

   name                 varchar(24), 

   age                  int, 

   primary key (id) 

);

 

public class User { 

    private Integer id; 

    private String name; 

    private Integer age; 

    public Integer getId() { 

        return id; 

    } 

    public void setId(Integer id) { 

        this.id = id; 

    } 

    public String getName() { 

        return name; 

    } 

    public void setName(String name) { 

        this.name = name; 

    } 

    public Integer getAge() { 

        return age; 

    } 

    public void setAge(Integer age) { 

        this.age = age; 

    } 

}

 

public interface IUserDAO { 

    public void insert(User user); 

    public User find(Integer id); 

}

 

/** 

* Created by IntelliJ IDEA.<br> 

* <b>User</b>: leizhimin<br> 

* <b>Date</b>: 2008-4-22 11:40:18<br> 

* <b>Note</b>: 子类DAO 

*/ 

public class UserDAO extends BaseDAO implements IUserDAO { 

    public void insert(User user) { 

        String name = user.getName(); 

        int age = user.getAge().intValue(); 

        Connection conn = null; 

        Statement stmt = null; 

        try { 

            conn = getConnection(); 

            stmt = conn.createStatement(); 

            stmt.execute("INSERT INTO user (name,age) " + "VALUES('" + name + "'," + age + ")"); 

        } catch (SQLException e) { 

            e.printStackTrace(); 

        } 

        finally { 

            if (stmt != null) { 

                try { 

                    stmt.close(); 

                } 

                catch (SQLException e) { 

                    e.printStackTrace(); 

                } 

            } 

            if (conn != null) { 

                try { 

                    conn.close(); 

                } 

                catch (SQLException e) { 

                    e.printStackTrace(); 

                } 

            } 

        } 

    } 

    public User find(Integer id) { 

        Connection conn = null; 

        Statement stmt = null; 

        try { 

            conn = getConnection(); 

            stmt = conn.createStatement(); 

            ResultSet result = stmt.executeQuery( 

                    "SELECT * FROM user WHERE id=" + id.intValue()); 

            if (result.next()) { 

                Integer i = new Integer(result.getInt(1)); 

                String name = result.getString(2); 

                Integer age = new Integer(result.getInt(3)); 

                User user = new User(); 

                user.setId(i); 

                user.setName(name); 

                user.setAge(age); 

                return user; 

            } 

        } catch (SQLException e) { 

            e.printStackTrace(); 

        } 

        finally { 

            if (stmt != null) { 

                try { 

                    stmt.close(); 

                } 

                catch (SQLException e) { 

                    e.printStackTrace(); 

                } 

            } 

            if (conn != null) { 

                try { 

                    conn.close(); 

                } 

                catch (SQLException e) { 

                    e.printStackTrace(); 

                } 

            } 

        } 

        return null; 

    } 

}

 

/** 

* Created by IntelliJ IDEA.<br> 

* <b>User</b>: leizhimin<br> 

* <b>Date</b>: 2008-4-22 13:53:56<br> 

* <b>Note</b>: 基类DAO,提供了数据源注入 

*/ 

public class BaseDAO { 

    private DataSource dataSource; 

    public DataSource getDataSource() { 

        return dataSource; 

    } 

    public void setDataSource(DataSource dataSource) { 

        this.dataSource = dataSource; 

    } 

    public Connection getConnection() { 

        Connection conn = null; 

        try { 

            conn = dataSource.getConnection(); 

        } catch (SQLException e) { 

            e.printStackTrace(); 

        } 

        return conn; 

    } 

}

<?xml version="1.0" encoding="UTF-8"?> 

<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" 

        "http://www.springframework.org/dtd/spring-beans.dtd"> 

<beans> 

    <bean id="dataSource" 

          class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 

        <property name="driverClassName"> 

            <value>com.mysql.jdbc.Driver</value> 

        </property> 

        <property name="url"> 

            <value>jdbc:mysql://localhost:3306/springdb</value> 

        </property> 

        <property name="username"> 

            <value>root</value> 

        </property> 

        <property name="password"> 

            <value>leizhimin</value> 

        </property> 

    </bean> 

    <bean id="baseDAO" class="com.lavasoft.springnote.ch05_jdbc02.BaseDAO" abstract="true"> 

        <property name="dataSource"> 

            <ref bean="dataSource"/> 

        </property> 

    </bean> 

    <bean id="userDAO" 

          class="com.lavasoft.springnote.ch05_jdbc02.UserDAO" parent="baseDAO"> 

    </bean> 

</beans>

 

/** 

* Created by IntelliJ IDEA.<br> 

* <b>User</b>: leizhimin<br> 

* <b>Date</b>: 2008-4-22 11:41:34<br> 

* <b>Note</b>: 客户端测试 

*/ 

public class SpringDAODemo { 

    public static void main(String[] args) { 

        ApplicationContext context = new FileSystemXmlApplicationContext("D:\\_spring\\src\\com\\lavasoft\\springnote\\ch05_jdbc02\\bean-jdbc.xml"); 

        User user = new User(); 

        user.setName("caterpillar"); 

        user.setAge(new Integer(30)); 

        IUserDAO userDAO = (IUserDAO) context.getBean("userDAO"); 

        userDAO.insert(user); 

        user = userDAO.find(new Integer(1)); 

        System.out.println("name: " + user.getName()); 

    } 

}

 

运行结果:

log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory). 

log4j:WARN Please initialize the log4j system properly. 

name: jdbctemplate 

Process finished with exit code 0

 

 

注意:Spring配置文件中对继承的配置,DataSource注入方式,通过继承来注入,从而简化编程。

 

上面用的是Spring的自己的数据源实现,现在假如要换成apache的DBCP数据源,则配置改为如下即可:

    <bean id="dataSource" 

          class="org.apache.commons.dbcp.BasicDataSource" singleton="true"> 

        <property name="driverClassName"> 

            <value>com.mysql.jdbc.Driver</value> 

        </property> 

        <property name="url"> 

            <value>jdbc:mysql://localhost:3306/springdb</value> 

        </property> 

        <property name="username"> 

            <value>root</value> 

        </property> 

        <property name="password"> 

            <value>leizhimin</value> 

        </property> 

    </bean>

 

实际上仅仅是更改一下数据源的calss实现。

 

 

 

 

 

 

©著作权归作者所有:来自51CTO博客作者leizhimin的原创作品,如需转载,请注明出处,否则将追究法律责任

配置应用SpringSpring


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消