1. 程式人生 > >Spring 框架系列之 JDBC 整合實例

Spring 框架系列之 JDBC 整合實例

nat ttr span ring 分享圖片 AC 增刪 not 增刪改

微信公眾號:compassblog

歡迎關註、轉發,互相學習,共同進步!

有任何問題,請後臺留言聯系!

1、Spring框架整合 DAO 模板

  • JDBC:org.springframework.jdbc.core.JdbcTemplate
  • Hibernate3.0:org.springframework.orm.hibernate3.HibernateTemplate
  • MyBatis:org.springframework.orm.ibatis.SqlMapClientTemplate
  • JPA:org.springframework.orm.jpa.JpaTemplate

2、JdbcTemplate 模板整合 JDBC 實例

(1)、新建web項目,導入所需要的 jar 包,如下圖所示:

技術分享圖片

(2)、在 MySQL 數據庫 JdbcTemplateDB 中新建數據表 t_user, 如下圖所示:

技術分享圖片

(3)、新建一個 bean 類,具體代碼如下:

User.java

package com.spring.bean;

public class User {
    private Integer id;
    private String name;
    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;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }
}

(4)、書寫 DAO 接口,代碼如下:

UserDao.java

package com.spring.dao;

import java.util.List;

import com.spring.bean.User;

public interface UserDao {

    //增
    void save(User u);
    //刪
    void delete(Integer id);
    //改
    void update(User u);
    //查
    User getById(Integer id);
    //查
    int getTotalCount();
    //查
    List<User> getAll();
}

(5)、書寫一個類實現 DAO 接口,代碼如下:

UserDaoImpl.java

package com.spring.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.spring.bean.User;

//使用JDBC模板實現增刪改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    public void save(User u) {
        String sql = "insert into t_user values(null,?) ";
        super.getJdbcTemplate().update(sql, u.getName());
    }
    public void delete(Integer id) {
        String sql = "delete from t_user where id = ? ";
        super.getJdbcTemplate().update(sql,id);
    }
    public void update(User u) {
        String sql = "update  t_user set name = ? where id=? ";
        super.getJdbcTemplate().update(sql, u.getName(),u.getId());
    }
    public User getById(Integer id) {
        String sql = "select * from t_user where id = ? ";
        return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }}, id);

    }
    public int getTotalCount() {
        String sql = "select count(*) from t_user  ";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    public List<User> getAll() {
        String sql = "select * from t_user  ";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }
}

(6)、新建數據庫驅動鏈接資源文件,代碼如下:

db.properties

jdbc.jdbcUrl=jdbc:mysql:///JdbcTemplateDB
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

(7)、書寫 Spring 配置文件,代碼如下:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!-- 指定spring讀取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 1.將數據庫連接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>


<!-- 2.將JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>

<!-- 3.將UserDao放入spring容器 -->
<bean name="userDao" class="com.spring.dao.UserDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>

</beans>

(8)、新建測試類進行測試,代碼如下:

TestDemo.java

package com.spring.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.spring.bean.User;
import com.spring.dao.UserDao;

//演示JDBC模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDemo {

    @Autowired
    private UserDao ud;

    @Test
    public void fun1() throws Exception{

        //1、準備連接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql:///JdbcTemplateDB");
        dataSource.setUser("root");
        dataSource.setPassword("root");
        //2、創建JDBC模板對象
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dataSource);
        //3、書寫sql語句,並執行
        String sql = "insert into t_user values(null,‘rose‘) ";
        jt.update(sql);

    }

    @Test
    public void fun2() throws Exception{
        User u = new User();
        u.setName("tom");
        ud.save(u);
    }
    @Test
    public void fun3() throws Exception{
        User u = new User();
        u.setId(2);
        u.setName("jack");
        ud.update(u);

    }

    @Test
    public void fun4() throws Exception{
        ud.delete(2);
    }

    @Test
    public void fun5() throws Exception{
        System.out.println(ud.getTotalCount());
    }

    @Test
    public void fun6() throws Exception{
        System.out.println(ud.getById(1));
    }

    @Test
    public void fun7() throws Exception{
        System.out.println(ud.getAll());
    }
}

(9)、配置依賴關系與使用圖解:

技術分享圖片

註:部分知識源於網絡,侵權聯刪除!

掃描關註微信公眾號,了解更多

技術分享圖片

Spring 框架系列之 JDBC 整合實例