SpringJDBC简介

时间:2020-02-23 14:29:27  来源:igfitidea点击:

在本教程中,我们将了解JDBC模块是什么,希望我们在阅读完之后能够找到用例。

现在,让我们创建一个表示员工的非常简单的表。

CREATE TABLE Employee (
 ID INT NOT NULL AUTO_INCREMENT,
 NAME VARCHAR(20) NOT NULL,
 AGE INT NOT NULL,
 DEPARTMENT VARCHAR(20) NOT NULL,
 PRIMARY KEY(ID)
);

springjdbc框架为我们节省了大量的时间和精力,因为它处理诸如初始化连接、执行SQL查询、关闭连接等低级细节。在这种情况下,我们可能会想知道还有什么事情需要我们去做。好吧,我们必须定义连接参数并指定要执行的SQL查询,最后,我们必须在从数据库中获取数据时为所有迭代编写逻辑。

有许多方法和已经编写的类可以帮助我们实现JDBC。在我们的例子中,我们将坚持使用经典的JDBC模板类。它将管理所有的数据库通信。

关于JDBC模板类,我们需要了解什么?简而言之,它捕捉JDBC异常,执行SQL查询和update语句。还需要注意的是,JDBC模板类的所有实例都是线程安全的,这意味着我们可以配置一个JDBC模板类的实例,并将其作为共享引用安全地注入到多个dao中。

如果我们不熟悉DAO是什么,可以查看我关于这个主题的文章。

现在是有趣的部分。让我们看看如何实现所有的理论。我们将使用教程开头所示的表。

EmployeeDAO.java

package com.tutorialnet;

import java.util.List;
import javax.sql.DataSource;

public interface EmployeeDAO {
 public void setDataSource(DataSource ds);

 public void create(String name, Integer age, String department);

 public Employee getEmployee(Integer id);

 public List<Employee> getEmployees();

 public void delete(Integer id);

 public void update(Integer id, Integer age, String department);
}

这是我们的DAO接口。它包含所有的方法声明,并且所有这些方法声明都与CRUD功能有关。

setDataSource():建立数据库连接。

create():将用于在数据库中新建职员条目。

getEmployee():根据提供的ID返回职员。

getEmployees():将返回数据库中所有员工的列表。

delete():根据提供的ID删除职员。

update():更新已有员工。

雇员.java

package com.theitroad;

public class Employee {
 private Integer id;
 private String name;
 private Integer age;
 private String department;

  public void setId(Integer id) {
    this.id = id;
 }

 public void setAge(Integer age) {
    this.age = age;
 }

 public void setName(String name) {
    this.name = name;
 }

 public void setDepartment(String department) {
     this.department = department;
 }

 public Integer getId() {
     return this.id;
 }    

 public Integer getAge() {
    return this.age;
 }

 public String getName() {
    return this.name;
 }

 public String getDepartment() {
     return this.department;
 }
}

EmployeeMapper.java

package com.theitroad;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class EmployeeMapper implements RowMapper<Employee> {
 public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
    Employee employee = new Employee();
    employee.setId(rs.getInt("id"));
    employee.setName(rs.getString("name"));
    employee.setAge(rs.getInt("age"));
    employee.setDepartment(rs.getString("department"));

    return employee;
 }
}

EmployeeJDBCTemplate.java

package com.theitroad;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class EmployeeJDBCTemplate implements EmployeeDAO {
 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 department) {
    String SQL = "insert into Employee (name, age, department) values (?, ?)";
    jdbcTemplateObject.update( SQL, name, age, department);
 }

 public Employee getEmployee(Integer id) {
    String SQL = "select * from Employee where id = ?";
    Employee employee = jdbcTemplateObject.queryForObject(SQL, 
       new Object[]{id}, new EmployeeMapper());

    return employee;
 }
 public List<Employee> getEmployees() {
    String SQL = "select * from Employee";
    List <Employee> employees = jdbcTemplateObject.query(SQL, new EmployeeMapper());
    return employees;
 }
 public void delete(Integer id) {
    String SQL = "delete from Employee where id = ?";
    jdbcTemplateObject.update(SQL, id);
    System.out.println("Deleted Record with ID = " + id );
 }

 public void update(Integer id, Integer age){
    String SQL = "update Employee set age = ? where id = ?";
    jdbcTemplateObject.update(SQL, age, id);
 }
}

这个JDBC类定义了我们上面定义的接口中的所有方法声明。

主类

package com.theitroad;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tutorialspoint.EmployeeJDBCTemplate;

public class Main {
 public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

    EmployeeJDBCTemplate employeeJDBCTemplate = (EmployeeJDBCTemplate)context.getBean("employeeJDBCTemplate");

    System.out.println("Creating records..." );
    employeeJDBCTemplate.create("Hyman", 11, "Software engineering");
    employeeJDBCTemplate.create("Joanna", 2, "Finance");
    employeeJDBCTemplate.create("Derek", 15, "Hardware engineering");

    System.out.println("Listing employee entries from the database..");
    List<Employee> employees = employeeJDBCTemplate.getEmployees();

    for (Employee employee : employees) {
       System.out.print("ID: " + employee.getId());
       System.out.print("Name: " + employee.getName());
       System.out.println("Age: " + employee.getAge());
       System.out.println("Age: " + employee.getDepartment());
    }

    System.out.println("Updating a record with an id of 1");
    employeeJDBCTemplate.update(1, 29, "Marketing");

    System.out.println("Displaying information about record with an id of 1");
    Employee employee = employeeJDBCTemplate.getEmployee(1);
    System.out.print("ID: " + employee.getId());
    System.out.print("Name : " + employee.getName() );
    System.out.println("Age : " + employee.getAge());
    ystem.out.println("Department : " + employee.getDepartment());
 }
}

这里我们调用接口中定义的所有方法。

的配置文件 **豆.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"
    <property name = "url" value = "jdbc:mysql://localhost:3306/DEMO"
    <property name = "username" value = "root"
    <property name = "password" value = "admin123"
 </bean>

 <bean id = "employeeJDBCTemplate" 
    class = "com.theitroad.EmployeeJDBCTemplate">
    <property name = "dataSource" ref = "dataSource"     
 </bean>

</beans>