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管理对象开发,一定要搞清楚对象之间的依赖关系。

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

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


    <property name="driverClass"value="com.mysql.jdbc.Driver?useUnicode=true&amp;characterEncoding=utf-8"></property>
    <property name="jdbcUrl"value="jdbc:mysql://localhost:3306/spring_jdbc"></property>
    <property name="user" value="root"></property>
    <property name="password"value="123"></property>
</bean>

<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource"ref="dataSource"></property>
</bean>

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

JdbcTemplateApi

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

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

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

@Override


public List<User> getAll() {
    String sql = "select *fromt_user";
    List<User> query = jdbcTemplate.query(sql,new RowMapper<User>() {
        @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

 

<!--读取db.properties文件-->


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

location是配置文件的地址

获得配置文件中的信息

<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>


具体代码奉上:

    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
">

    <!--读取db.properties文件-->
    <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="com.mysql.jdbc.Driver?useUnicode=true&amp;characterEncoding=utf-8"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_jdbc"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123"></property>-->

        <!--读取后的写法-->
        <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="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean name="userDao" class="cn.hd.spring_jdbc.impl.UserDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>-->

    <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&amp;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<User> 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<User> getAll() {
        String sql = "select *from t_user";
        /*List<User> query = jdbcTemplate.query(sql, new RowMapper<User>() {*/
        List<User> query = this.getJdbcTemplate().query(sql, new RowMapper<User>() {
            @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<User>() {
            @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<User> 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();
    }
}

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值