Spring 整合JDBC,你应该知道的。

Spring是一个容器。

Spring有个jar包提供了一个叫做JDBCTenplate模板,所以他能对数据库操作。Spring还提供了很多的模板针对hibernate、Mybatis模板。JDBCTemplate跟Dbutils中的QueryRunner极度相似。

整合JDBC(手动创建对象)


1、导包

C3p0、JDBC驱动,spring-jdbc  spring-tx


2、使用一个JdbcTemplate模板对数据库进行操作。


给他连接  Connection 给一个DataSource,需要数据库连接。

package cn.hd.spring_jdbc;


import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import java.beans.PropertyVetoException;

public class Demo {
    @Test
    public void fun1() throws PropertyVetoException{
        /*c3p0的数据库连接池*/
        ComboPooledDataSource dataSource= new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver?seUnicode=true&characterEncoding=UTF-8");
       dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring_jdbc");
        dataSource.setUser("root");
        dataSource.setPassword("123");

        JdbcTemplate jdbcTemplate = new JdbcTemplate();
       jdbcTemplate.setDataSource(dataSource);
        String sql="INSERT INTOt_user(uname,ubalance) VALUE('杨二狗',1)";
        jdbcTemplate.update(sql);
        //jdbcTemplate.query();
    }
}

spring管理对象的方式

UserDao接口 UserDaoImpl实现类  applicationContext.xml


Spring 整合JDBC,你应该知道的。_第1张图片

使用spring管理对象开发,一定要搞清楚对象之间的依赖关系。

然后将对应的bean类配置到文件中,将属性的的注入写好。


   
   
   
   



   



   

JdbcTemplateApi

增删改:调用JDBCTemplateupdate方法,如果有参数,直接按照顺序写在方法后面即可。

int update = jdbcTemplate.update(sql,user.getUname(), user.getUbalance());

查询:调用JDBCTemplatequery方法 参数同上。结果集处理,要传一个RowMapper匿名内部类。

@Override


public List getAll() {
    String sql = "select *fromt_user";
    List query = jdbcTemplate.query(sql,new RowMapper() {
        @Nullable
        @Override
        public User mapRow(ResultSetresultSet, int i) throws SQLException {
            User user = new User();
            user.setUid(resultSet.getInt("uid"));
           user.setUname(resultSet.getString("uname"));
           user.setUbalance(resultSet.getInt("ubalance"));
            return user;
        }
    });
    return query;
}

Spring  提供了一个父类,JdbcDaoSupport,这个父类中提供了JdbcTemplate模板,并且在配置bean时,依赖关系改变,dao类时直接依赖于DataSource。

如何使用spring读取配置文件

db.properties  书写配置文件是要注意  键名必须要加前缀,避免和关键字重复。

如歌读取配置文件    在applicationContext.xml中加上一条配置。注意使用context不能使用p标签,context标签中包含p标签。

xmlns:context="http://www.springframework.org/schema/context"

http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context.xsd

 


location是配置文件的地址

获得配置文件中的信息




具体代码奉上:

    applicationContext.xml

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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
">

    
    <context:property-placeholder location="classpath:cn/hd/spring_jdbc/db.properties">context:property-placeholder>

    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        

        
        <property name="driverClass" value="${jdbc.driverClass}">property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}">property>
        <property name="user" value="${jdbc.user}">property>
        <property name="password" value="${jdbc.password}">property>
    bean>

    

    <bean name="userDao" class="cn.hd.spring_jdbc.impl.UserDaoImpl">
        <property name="dataSource" ref="dataSource">property>
    bean>
beans>

db.properties

jdbc.driverClass = com.mysql.jdbc.Driver?useUnicode=true&characterEncoding=utf-8
jdbc.jdbcUrl = jdbc:mysql://localhost:3306/spring_jdbc
jdbc.user = root
jdbc.password = 123

User类

    

package cn.hd.spring_jdbc;

public class User {
    private Integer uid;
    private String uname;
    private Integer ubalance;

    public User() {
    }

    public User(Integer uid, String uname, Integer ubalance) {
        this.uid = uid;
        this.uname = uname;
        this.ubalance = ubalance;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public Integer getUbalance() {
        return ubalance;
    }

    public void setUbalance(Integer ubalance) {
        this.ubalance = ubalance;
    }

    @Override
    public String toString() {
        return "User:" +
                "uid=" + uid + "\t" +
                "uname=" + uname + "\t" +
                "ubalance=" + ubalance+"\n";
    }
}

UserDao

package cn.hd.spring_jdbc;

import java.util.List;

public interface UserDao {
    /*增*/
    int add(User user);
    /*删*/
    int delete(Integer uid);
    /*改*/
    int update(User user);
    /*查所有*/
    List getAll();
    /*查一个*/
    User getById(Integer id);

}

UserDaoImpl

package cn.hd.spring_jdbc.impl;

import cn.hd.spring_jdbc.User;
import cn.hd.spring_jdbc.UserDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.lang.Nullable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {

   /* private JdbcTemplate jdbcTemplate;
    *//*为了注入spring容器*//*
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }*/

    @Override
    public int add(User user) {
       String sql = "INSERT INTO t_user(uname,ubalance) VALUES (?,?)";
        /*int add = jdbcTemplate.update(sql, user.getUname(), user.getUbalance());*/
        int add = this.getJdbcTemplate().update(sql, user.getUname(), user.getUbalance());
        return add;
    }

    @Override
    public int delete(Integer uid) {
        String sql = "DELETE FROM t_user where uid = ?";
        int delete = this.getJdbcTemplate().update(sql, uid);
        return delete;
    }

    @Override
    public int update(User user) {
        String sql = "UPDATE t_user SET uname=?,ubalance=? where uid=?";
        int update = this.getJdbcTemplate().update(sql, user.getUname(), user.getUbalance(), user.getUid());
        return update;
    }

    @Override
    public List getAll() {
        String sql = "select *from t_user";
        /*List query = jdbcTemplate.query(sql, new RowMapper() {*/
        List query = this.getJdbcTemplate().query(sql, new RowMapper() {
            @Nullable
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setUid(resultSet.getInt("uid"));
                user.setUname(resultSet.getString("uname"));
                user.setUbalance(resultSet.getInt("ubalance"));
                return user;
            }
        });
        return query;
    }

    @Override
    public User getById(Integer id) {
        String sql = "select * from t_user where uid = ?";
        User user = this.getJdbcTemplate().queryForObject(sql, new RowMapper() {
            @Nullable
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setUid(resultSet.getInt("uid"));
                user.setUname(resultSet.getString("uname"));
                user.setUbalance(resultSet.getInt("ubalance"));
                return user;
            }
        }, id);
        return user;
    }
}
Demo1测试代码

package cn.hd.spring_jdbc;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:cn/hd/spring_jdbc/applicationContext.xml")
public class Demo1 {
    @Resource(name = "userDao")
    private UserDao userDao;
    @Test
    public void fun1(){
        User user = new User();
        user.setUname("李飞飞");
        user.setUbalance(100);
        int add = userDao.add(user);
        System.out.println(add);
    }
    @Test
    public void fun2(){
        int delete = userDao.delete(4);
        System.out.println(delete);
    }
    @Test
    public void fun3(){
        User user = new User();
        user.setUid(1);
        user.setUname("挖掘机");
        user.setUbalance(10);
        int update = userDao.update(user);

        System.out.println(update);
    }
    @Test
    public void fun4(){
        List all = userDao.getAll();
        System.out.println(all);
    }
    @Test
    public void fun5(){
        User user = userDao.getById(6);
        System.out.println(user);

    }

}
Demo测试代码

package cn.hd.spring_jdbc;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import java.beans.PropertyVetoException;

public class Demo {
    @Test
    public void fun1() throws PropertyVetoException {
        /*c3p0的数据库连接池*/
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver?useUnicode=true&characterEncoding=utf-8");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring_jdbc");
        dataSource.setUser("root");
        dataSource.setPassword("123");

        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        String sql="INSERT INTO t_user(uname,ubalance) VALUES ('二狗',1)";
        jdbcTemplate.update(sql);
        //jdbcTemplate.query();
    }
}

你可能感兴趣的:(Spring框架)