发表于: 2017-07-09 11:56:58

2 1287


今天完成的事:换掉教程果然很快就能解决问题

利用JDBCTemplate实现增删查改

在教程中叫做,spring JDBC,说明这个和spring框架息息相关。

直接贴代码

框架图


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(StudentDao实现类)

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


存储过程的sql命令

  1. delimiter //

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

  3. create procedure `test`.`getRecord`(

  4. IN in_id integer,

  5. out out_name varchar(20),

  6. out out_age integer

  7. )

  8. begin

  9.   select name,age

  10.   into out_name,out_age

  11.   from Student where id = in_id;

  12. end

  13.  // 

  14. delimiter ;


StudentMapper.java

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());

       }
*/
   }
}


最后成功实现

里面涉及了一些新知识,吃完饭回来讲。


继续

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

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


这里单条记录查询使用了存储过程方法来获取单条数据,用RowMapper来打印整个列表;


存储过程Procedure是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给定参数(如果该存储过程带有参数)来调用执行它;只简单了解了一下,以后用到再深入了解。


RowMapper

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

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


使用ApplicationContext对象,通过ClassPathXmlApplicationContext对象和context.getBean()方法获取beans。


最后着重讲beans.xml配置文件

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

第二块bean部分

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

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

即是连接了dataSource

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

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

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

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

可以看到文件中ref了dataSource


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



在任务一的项目中完成实现,并且单条记录查询不再使用存储过程,而是使用JDBCTemplate.queryForObject的方法。

余下的时间看spring,然后再说


收获:JDBCTemplate实现增删查改!又掌握一点spring框架的知识;又掌握一点bean.xml配置文件的知识。


返回列表 返回列表
评论

    分享到