码迷,mamicode.com
首页 > 数据库 > 详细

Spring整合JDBC

时间:2020-02-14 18:30:04      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:private   查询   apr   return   upd   HERE   ext   password   sql语句   

1、Spring整合JDBC

(1)导包(共12个):

c3p0连接池、JDBC驱动(4个)

Spring-jdbc、Spring-tx事务(2个)

技术图片

 

 (2)JDBC模板对象(JDBCTemplate)

public class JDBCDemo {
    public void test() throws PropertyVetoException {
        ComboPooledDataSource comboPooledDataSource=new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
        comboPooledDataSource.setJdbcUrl("jdbc:mysql:///stu_mangement");
        comboPooledDataSource.setPassword("root");
        comboPooledDataSource.setUser("root");
        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        jdbcTemplate.setDataSource(comboPooledDataSource);
        String sql="INSERT INTO student VALUES(‘201816‘,‘1998-11-11‘,‘tx101‘,‘19837372534‘,‘男‘,‘jiayou‘,‘892‘)";
        jdbcTemplate.update(sql);
    }
    public static void main(String[] args) throws PropertyVetoException {
        JDBCDemo jdbcDemo=new JDBCDemo();
        jdbcDemo.test();
    }
}

需要先创建连接池,获取comboPooledDataSource对象,将该对象给模板对象,最后,利用模板对象执行sql语句。但是,这种方法是手动创建对象的,没有体现Spring的IoC特性。

2、连接池、JDBC模板、Dao配置到Spring容器

(1)创建数据库(学生信息):

技术图片

 

 (2)创建一个接口,指定实现类的方法:

import java.util.List;
public interface StudentDao {
    void add(Student student);
    void delete(Integer studentno);
    void update(Student student);
    Student getStudentByNum(Integer studentno);
    int getTotalCount();
    List<Student> getAll();
}

(3)创建实现类,实现接口中的方法:

添加学生信息:

public void add(Student student) {
        String sql="INSERT INTO student VALUES(?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql,
                student.getStudentno(),
                student.getBirthday(),
                student.getClassno(),
                student.getPhone(),
                student.getSex(),
                student.getSname(),
                student.getPoint());
    }

根据学生的学号删除学生信息:

    public void delete(Integer studentno){
        String sql="delete from student where studentno=?";
        jdbcTemplate.update(sql,studentno);
    }

修改学生信息:

public void update(Student student) {
        String sql="update student set phone=? where studentno=?";
        jdbcTemplate.update(sql,student.getPhone(),student.getStudentno());
    }
public static void main(String [] args){
            ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");//创建容器对象
            StudentDao studentDao  =(StudentDao)applicationContext.getBean("studentDao");
            Student student=new Student();
            student.setStudentno(201811);
            student.setPhone("1234567890");
            studentDao.update(student);
    }

根据学号查询学生信息:

  public Student getStudentByNum(Integer studentno) {
        String sql="select * from student where studentno=?";
        return jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student=new Student();
                student.setStudentno(resultSet.getInt("studentno"));
                student.setSname(resultSet.getString("sname"));
                return student;
            }
        },
                studentno);//这个studentno是参数传过来的
    }

利用匿名内部类创建一个RowMapper,并实现该内部类里面的方法,获取一个student的对象,通过传递参数(studentno)返回符合条件的Student。

Student{sname=‘jiayou‘, studentno=201816, birthday=‘null‘, classno=‘null‘, phone=‘null‘, sex=‘null‘, point=null}

获取学生的数量:

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

传递参数的时候需要指明返回的结果的数据类型,用Integer.class。

获取全部学生信息:

public List<Student> getAll() {
        String sql="select * from student";
        List<Student> list=jdbcTemplate.query(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student=new Student();
                student.setStudentno(resultSet.getInt("studentno"));
                student.setSname(resultSet.getString("sname"));
                student.setPhone(resultSet.getString("phone"));
                student.setSex(resultSet.getString("sex"));
                student.setPoint(resultSet.getFloat("point"));
                student.setClassno(resultSet.getString("classno"));
                student.setBirthday(resultSet.getString("birthday"));
                return student;
            }
        });
        return list;
    }

与通过学号获取学生的信息不同,获取全部学生的信息的时候不需要传递参数,因此,query方法中参数的数量为2。

(4)配置文件:只有配置好了配置文件后才能获取到对象

<?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:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
       http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--将连接池放入Spring容器-->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///stu_mangement"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
<!--将JDBCTemplate放入Spring容器-->
    <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--将StudentDao放入Spring容器中-->
    <bean name="studentDao" class="pers.zhb.jdbc.StudentDaoImp">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
</beans>

通过配置文件,将以前手动创建对象的方式变成了通过配置文件获取对象。在这里用到了属性的注入,要注意基本数据类型和引用数据类型属性的区别。

(5)测试类:

public class Test {
    public static void main(String [] args){
            ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");//创建容器对象
            StudentDao studentDao  =(StudentDao)applicationContext.getBean("studentDao");
            List<Student> list =studentDao.getAll();
            System.out.println(list);
    }
}

(6)StudentDaoImp类:

public class StudentDaoImp implements StudentDao{
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void add(Student student) {
        String sql="INSERT INTO student VALUES(?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql,
                student.getStudentno(),
                student.getBirthday(),
                student.getClassno(),
                student.getPhone(),
                student.getSex(),
                student.getSname(),
                student.getPoint());
    }

    @Override
    public void delete(Integer studentno){
        String sql="delete from student where studentno=?";
        jdbcTemplate.update(sql,studentno);
    }

    @Override
    public void update(Student student) {
        String sql="update student set phone=? where studentno=?";
        jdbcTemplate.update(sql,student.getPhone(),student.getStudentno());
    }

    @Override
    public Student getStudentByNum(Integer studentno) {
        String sql="select * from student where studentno=?";
        return jdbcTemplate.queryForObject(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student=new Student();
                student.setStudentno(resultSet.getInt("studentno"));
                student.setSname(resultSet.getString("sname"));
                return student;
            }
        },
                studentno);//这个studentno是参数传过来的
    }

    @Override
    public int getTotalCount() {
        String sql="select count(*) from student";
        Integer count =jdbcTemplate.queryForObject(sql,Integer.class);
        return count;
    }

    @Override
    public List<Student> getAll() {
        String sql="select * from student";
        List<Student> list=jdbcTemplate.query(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student=new Student();
                student.setStudentno(resultSet.getInt("studentno"));
                student.setSname(resultSet.getString("sname"));
                student.setPhone(resultSet.getString("phone"));
                student.setSex(resultSet.getString("sex"));
                student.setPoint(resultSet.getFloat("point"));
                student.setClassno(resultSet.getString("classno"));
                student.setBirthday(resultSet.getString("birthday"));
                return student;
            }
        });
        return list;
    }
}

另外一种方法:不需要手动书写JDBC模板对象,直接从父类中获取即可:

public class StudentDaoImp extends JdbcDaoSupport implements StudentDao{
    @Override
    public void add(Student student) {
        String sql="INSERT INTO student VALUES(?,?,?,?,?,?,?)";
        super.getJdbcTemplate().update(sql,
                student.getStudentno(),
                student.getBirthday(),
                student.getClassno(),
                student.getPhone(),
                student.getSex(),
                student.getSname(),
                student.getPoint());
    }

    @Override
    public void delete(Integer studentno){
        String sql="delete from student where studentno=?";
        super.getJdbcTemplate().update(sql,studentno);
    }

    @Override
    public void update(Student student) {
        String sql="update student set phone=? where studentno=?";
        super.getJdbcTemplate().update(sql,student.getPhone(),student.getStudentno());
    }

    @Override
    public Student getStudentByNum(Integer studentno) {
        String sql="select * from student where studentno=?";
        return super.getJdbcTemplate().queryForObject(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student=new Student();
                student.setStudentno(resultSet.getInt("studentno"));
                student.setSname(resultSet.getString("sname"));
                return student;
            }
        },
                studentno);//这个studentno是参数传过来的
    }

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

    @Override
    public List<Student> getAll() {
        String sql="select * from student";
        List<Student> list=super.getJdbcTemplate().query(sql, new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet resultSet, int i) throws SQLException {
                Student student=new Student();
                student.setStudentno(resultSet.getInt("studentno"));
                student.setSname(resultSet.getString("sname"));
                student.setPhone(resultSet.getString("phone"));
                student.setSex(resultSet.getString("sex"));
                student.setPoint(resultSet.getFloat("point"));
                student.setClassno(resultSet.getString("classno"));
                student.setBirthday(resultSet.getString("birthday"));
                return student;
            }
        });
        return list;
    }
}

此时的配置文件少了一个继承关系:

<!--将连接池放入Spring容器-->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///stu_mangement"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
<!--将StudentDao放入Spring容器中-->
    <bean name="studentDao" class="pers.zhb.jdbc.StudentDaoImp">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

因为JDBCDaoSupport是根据连接池创建的JDBC模板,不需要再手动获取了。

3、配置文件有关JDBC的优化

(1)创建db.properties配置文件:

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

(2)在spring的配置文件中读取db.properties配置文件的数据:

<!--指定要读取的配置文件的位置-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!--将连接池放入Spring容器-->
    <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>
<!--将StudentDao放入Spring容器中-->
    <bean name="studentDao" class="pers.zhb.jdbc.StudentDaoImp">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

这种方式虽然创建了两个配置文件看上去比较繁琐,但是,这种方式是有利于后期的维护的:方便对JDBC有关参数的修改。

 

Spring整合JDBC

标签:private   查询   apr   return   upd   HERE   ext   password   sql语句   

原文地址:https://www.cnblogs.com/zhai1997/p/12304072.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!