JDBCTemplate实现增删查改

来源:互联网 发布:扫描软件安装哪里 编辑:程序博客网 时间:2024/06/05 13:53

转载注明出处


今天终于把这两天一直困扰我的问题解决了,就是利用JDBCTemplate实现增删查改,对数据库进行操作。

直接进入正题

先贴框架


需要导入的jar包

junit;spring-context;spring-jdbc;mysql-connector-java。


然后是代码部分

Student.java

package com.jdbct;/** * Created by Administrator on 2017/07/08. */public class Student {    private Integer id;    private String name;    private Integer age;    public int 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 int getAge(){return age;}    public void setAge(Integer age){        this.age=age;    }    @Override    public String toString() {        return "Student{" +                "id=" + id +                ", name='" + name + '\'' +                '}';    }}

StudentDao.java

package com.jdbct.dao;import com.jdbct.Student;import javax.sql.DataSource;import java.util.List;/** * Created by Administrator on 2017/07/08. */public interface StudentDao {    /*This is the method to be used to initialize database resources*/   public void setDataSource(DataSource ds);   /*This is the method to be used to create a record in the Student table.*/   public void create(String name,Integer age);   public Student getStudent(Integer id);   public void deleteById(Integer id);   public void update(Integer id,String name,Integer age);   //This is the method to be used to list down all the records from the Student table.    public List<Student> listStudents();}

StudentJDBCTemplate.java(接口实现类)

package com.jdbct.dao;import com.jdbct.Student;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;import org.springframework.jdbc.core.namedparam.SqlParameterSource;import org.springframework.jdbc.core.simple.SimpleJdbcCall;import javax.sql.DataSource;import java.util.List;import java.util.Map;/** * Created by Administrator on 2017/07/09. */public class StudentJDBCTemplate implements StudentDao{    private DataSource dataSource;    private JdbcTemplate jdbcTemplateObject;    public void setDataSource(DataSource dataSource){        this.dataSource = dataSource;        this.jdbcTemplateObject = new JdbcTemplate(dataSource);    }    public void create(String name,Integer age){        String SQL = "insert into Student(name,age) values(?,?)";        jdbcTemplateObject.update(SQL,name,age);        System.out.println("Created Record Name = " + name + " Age = " + age);        return;    }    public void deleteById(Integer id){        String SQL = "delete  from Student where id=?";        jdbcTemplateObject.update(SQL,id);        System.out.println("Delete Record with ID = " + id);        return;    }    public void update(Integer id, String name, Integer age) {        String SQL = "update Student set name=?,age=? where id=?";        jdbcTemplateObject.update(SQL,name,age,id);        System.out.println("Update Record with ID =" + id);        return;    }    public List<Student> listStudents(){        String SQL = "select * from Student";        List<Student> students = jdbcTemplateObject.query(SQL,new StudentMapper());        return students;    }    public Student getStudent(Integer id){        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getRecord");        SqlParameterSource in = new MapSqlParameterSource().addValue("in_id",id);        Map<String,Object> out = jdbcCall.execute(in);        Student student = new Student();        student.setId(id);        student.setName((String) out.get("out_name"));        student.setAge((Integer) out.get("out_age"));        return student;    }}

StudentMapper.java

package com.jdbct.dao;import com.jdbct.Student;import org.springframework.jdbc.core.RowMapper;import java.sql.ResultSet;import java.sql.SQLException;/** * Created by Administrator on 2017/07/08. */public class StudentMapper implements RowMapper<Student> {    public Student mapRow(ResultSet rs, int rowNum) throws SQLException {        Student student = new Student();        student.setId(rs.getInt("id"));        student.setName(rs.getString("name"));        student.setAge(rs.getInt("age"));        return student;    }}

beans.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"       xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <!--数据库驱动-->        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>        <!--数据库连接的URL-->        <property name="url" value="jdbc:mysql://localhost:3306/test"/>        <!--数据库连接的用户名-->        <property name="username" value="root"/>        <!--数据库连接的密码-->        <property name="password" value="yubotao9527"/>    </bean>    <bean id="studentJDBCTemplate"          class="com.jdbct.dao.StudentJDBCTemplate">        <property name="dataSource"><ref bean="dataSource"/></property>    </bean></beans>

MainApp.java(测试类)

import com.jdbct.Student;import com.jdbct.dao.StudentJDBCTemplate;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Created by Administrator on 2017/07/08. */public class MainApp {    public static void main(String[] args){        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");        StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate" );        /*        System.out.println("----------Record Creation----------");        studentJDBCTemplate.create("Maxsu",19);        studentJDBCTemplate.create("Youga",23);        studentJDBCTemplate.create("Make",35);        */        System.out.println("----------Getting Record with ID = 3----------");        Student stu = studentJDBCTemplate.getStudent(3);        System.out.print("ID : " + stu.getId());        System.out.print(", Name : " + stu.getName());        System.out.println(", Age : " + stu.getAge());/*        System.out.println("----------Deleting Record with ID = 2----------");        studentJDBCTemplate.deleteById(2);*//*        System.out.println("----------Updating Record with ID = 2----------");        studentJDBCTemplate.update(5,"Franklin",25);*//*        System.out.println("----------Listing Multiple Creation----------");        List<Student> students = studentJDBCTemplate.listStudents();        for(Student record:students){            System.out.print("ID :"+record.getId());            System.out.print(",Name :"+record.getName());            System.out.println(",Age :"+record.getAge());        }*/    }}

最后成功实现JDBCTemplate对数据库的增删查改操作


这里要讲一下实现查找操作的getStudent方法,这里使用了数据库的存储过程方法

创建存储过程的sql命令如下

  • delimiter //

  • drop procedure if exists `test`.`getRecord` //

  • create procedure `test`.`getRecord`(

  • IN in_id integer,

  • out out_name varchar(20),

  • out out_age integer

  • )

  • begin

  •   select name,age

  •   into out_name,out_age

  •   from Student where id = in_id;

  • end

  •  // 

  • delimiter ;

    这里的delimiter是分隔符的意思,具体什么情况自行百度。procedure就是存储过程。


    新的东西就只有

    DataSource接口,javax.sql.DataSource)替代DriverManager获取Connection的方法,就是用来和数据库连接的;

    JDBCTemplate利用JDBCTemplate.update()方法用来更新数据,用JDBCTemplate.query()方法进行查询;

    讲到这里,就提一下另一种实现查询单条记录的实现方法,就是JDBCTemplate.queryForObject()方法,具体可以百度一下,我直接贴代码实现

    public Student selectStudent(int id){    String sql = "select * from businesstable where ID = ?";    Student student = jdbcTemplateObject.queryForObject(sql,new Object[]{id},new StudentMapper());    return student;}

    什么意思自己体会,不懂就百度。


    ping中的RowMapper可以将数据中的每一行数据封装成用户定义的类。可以通过建立内部类实现RowMapper接口,RowMapper中有一个mapRow方法,所以实现RowMapper接口一定要实现mapRow方法,而对自定义类的包装就在mapRow方法中实现。

    简单来说,用RowMapper来打印列表。


    最后就是beans.xml配置文件

    第一块的bean部分是用来连接数据的

    第二块bean部分

    id是一个标识,class是该标识的路径;

    property,以此方式可以通过配置为连接数据的属性赋值

    即是连接了dataSource

    这个bean要有一个setter方法,就在路径文件内,可见文件中有setDataSource方法

    基本数据类型,可以通过setter方法为对象中的属性设置初始值

    如果属性的类型不是基本类型或String ,可以使用引用的方式为对象赋值(bean中property中的ref)

       扩展-以此方式可以把数据库的连接值给实现类赋值

    可以看到文件中ref了dataSource


    然后在测试类中我们可以看到,并没有新建studentJDBCTemplate对象,这都在bean.xml文件中配置,spring框架自动生成的对象,我们测试时直接使用方法就行了。


    最后的最后,总结一下:JDBCTemplate实现增删查改相较于jdbc实现,减少了代码量,增加了可靠性,而且用到了spring框架的知识,可以扩大知识面;但是相较于mybatis还是有一点差距,灵活性没有mybatis好,也没有mybatis方便,简洁,mybatis的代码量更少。