在Java的Spring框架的法式中應用JDBC API操作數據庫。本站提示廣大學習愛好者:(在Java的Spring框架的法式中應用JDBC API操作數據庫)文章只能為提供參考,不一定能成為您想要的結果。以下是在Java的Spring框架的法式中應用JDBC API操作數據庫正文
同時與數據庫應用通俗的舊JDBC的任務,它變得繁瑣寫不用要的代碼來處置異常,翻開和封閉數據庫銜接等,但Spring的JDBC框架須要的一切低條理細節從翻開銜接,預備和履行SQL語句,進程異常,處置事務,最初封閉銜接。
所以,你所要做的只是界說銜接參數,並指定要履行的SQL語句,並做需要的任務,在每次迭代時從數據庫中獲得數據。
Spring JDBC供給了一些辦法和響應分歧的類與數據庫停止交互。我要采用經典和最風行的做法,應用JdbcTemplateclass框架。這是治理的一切數據庫的通訊和異常處置中間框架類。
JdbcTemplate 類
JdbcTemplate類履行SQL查詢,更新語句和存儲進程挪用,在成果集和提取前往參數值停止迭代。它還捕獲JDBC的異常並將其轉換為通用的,信息更豐碩,除在org.springframework.dao包中界說的條理構造。
JdbcTemplate類的實例是一次設置裝備擺設的線程。所以,你可以設置裝備擺設一個JdbcTemplate的一個實例,然後平安地注入這類同享援用到多個DAO。
應用JdbcTemplate類時,平日的做法是設置裝備擺設一個DataSource在Spring設置裝備擺設文件,然後依附關系注入該同享數據源豆到DAO類,JdbcTemplate或許是在setter數據源創立。
設置裝備擺設數據源
讓我們一路發明數據庫test數據庫表的 student 。假定應用MySQL數據庫,假如應用其他數據庫,那末可以響應地轉變你的DDL和SQL查詢。
CREATE TABLE Student( ID INT NOT NULL AUTO_INCREMENT, NAME VARCHAR(20) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID) );
如今,我們須要供給一個數據源給JdbcTemplate類,是以它可以自行設置裝備擺設,以取得數據庫拜訪。您可以設置裝備擺設數據源的XML文件中有一段代碼,以下圖所示:
<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/TEST"/> <property name="username" value="root"/> <property name="password" value="password"/> </bean>
數據拜訪對象 (DAO)
DAO表現這是平日用於數據庫交互的數據拜訪對象。 DAO的存在是為了供給讀取和寫入數據到數據庫中,他們應當經由過程該運用法式的其他部門將拜訪它們的接口地下此功效的一種手腕。
在Spring的數據拜訪對象(DAO)的支撐使得它很輕易與如JDBC,Hibernate,JPA和JDO以分歧的方法停止數據拜訪技巧。
履行SQL語句
讓我們來看看若何應用SQL和的JdbcTemplate對象數據庫中的表履行CRUD(創立,讀取,更新和刪除)操作。
查詢一個整數:
String SQL = "select count(*) from Student"; int rowCount = jdbcTemplateObject.queryForInt( SQL );
查詢長整數:
String SQL = "select count(*) from Student"; long rowCount = jdbcTemplateObject.queryForLong( SQL );
應用綁定變量的簡略查詢:
String SQL = "select age from Student where id = ?"; int age = jdbcTemplateObject.queryForInt(SQL, new Object[]{10});
在查詢字符串:
String SQL = "select name from Student where id = ?"; String name = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, String.class);
查詢並前往一個對象:
String SQL = "select * from Student where id = ?"; Student student = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, new StudentMapper()); 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; } }
查詢並前往多個對象:
String SQL = "select * from Student"; List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper()); 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; } }
拔出一行到表:
String SQL = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL, new Object[]{"Zara", 11} );更新一行到表:
String SQL = "update Student set name = ? where id = ?"; jdbcTemplateObject.update( SQL, new Object[]{"Zara", 10} );
從表中刪除行:
String SQL = "delete Student where id = ?"; jdbcTemplateObject.update( SQL, new Object[]{20} );
履行DDL語句
您可使用execute(...)辦法的JdbcTemplate來履行任何SQL語句或DDL語句。上面是一個示例應用CREATE語句創立一個表:
String SQL = "CREATE TABLE Student( " + "ID INT NOT NULL AUTO_INCREMENT, " + "NAME VARCHAR(20) NOT NULL, " + "AGE INT NOT NULL, " + "PRIMARY KEY (ID));" jdbcTemplateObject.execute( SQL );
SQL存儲進程
SimpleJdbcCall的類可以用來挪用帶有IN和OUT參數的存儲進程。你可使用這類辦法,而與任何愛好的Apache Derby,DB2,MySQL和微軟SQL辦事器,Oracle和Sybase RDBMS中的任務。
其次,斟酌以下的MySQL存儲進程這須要先生證和用OUT參數對應的先生的姓名和年紀的報答。是以,讓我們應用MySQL敕令提醒符下在測試數據庫中創立該存儲進程:
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 ;
如今讓我們寫了Spring JDBC運用法式,將履行我們的先生桌簡略的創立和讀取操作。
來創立一個Spring運用法式:
以下是數據拜訪對象接口文件StudentDAO.java的內容:
package com.yiibai; import java.util.List; import javax.sql.DataSource; public interface StudentDAO { /** * This is the method to be used to initialize * database resources ie. connection. */ 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); /** * This is the method to be used to list down * a record from the Student table corresponding * to a passed student id. */ public Student getStudent(Integer id); /** * This is the method to be used to list down * all the records from the Student table. */ public List<Student> listStudents(); }
以下是Student.java文件的內容:
package com.yiibai; public class Student { private Integer age; private String name; private Integer id; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } }
以下是StudentMapper.java文件的內容:
package com.yiibai; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; 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; } }
上面是完成類文件StudentJDBCTemplate.java界說DAO接口StudentDAO:
package com.yiibai; import java.util.Map; import javax.sql.DataSource; 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; public class StudentJDBCTemplate implements StudentDAO { private DataSource dataSource; private SimpleJdbcCall jdbcCall; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcCall = new SimpleJdbcCall(dataSource). withProcedureName("getRecord"); } public void create(String name, Integer age) { JdbcTemplate jdbcTemplateObject = new JdbcTemplate(dataSource); String SQL = "insert into Student (name, age) values (?, ?)"; jdbcTemplateObject.update( SQL, name, age); System.out.println("Created Record Name = " + name + " Age = " + age); return; } public Student getStudent(Integer id) { 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; } public List<Student> listStudents() { String SQL = "select * from Student"; List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper()); return students; } }
關於下面的法式幾句話:你寫的挪用的履行代碼時,須要創立包括IN參數的一個SqlParameterSource。主要的是要合營供給與存儲進程中聲明的參數名的輸出值的稱號。 execute辦法吸收傳入的參數,並前往包括任何列在存儲進程中指定的稱號鍵入參數的映照。如今讓我們修正主運用法式文件MainApp.java,這是以下:
package com.yiibai; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiibai.StudentJDBCTemplate; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); System.out.println("------Records Creation--------" ); studentJDBCTemplate.create("Zara", 11); studentJDBCTemplate.create("Nuha", 2); studentJDBCTemplate.create("Ayan", 15); System.out.println("------Listing Multiple Records--------" ); 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()); } System.out.println("----Listing Record with ID = 2 -----" ); Student student = studentJDBCTemplate.getStudent(2); System.out.print("ID : " + student.getId() ); System.out.print(", Name : " + student.getName() ); System.out.println(", Age : " + student.getAge()); } }
以下是設置裝備擺設文件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 "> <!-- Initialization for data source --> <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/TEST"/> <property name="username" value="root"/> <property name="password" value="password"/> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id="studentJDBCTemplate" class="com.yiibai.StudentJDBCTemplate"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
創立源代碼和bean設置裝備擺設文件完成後,讓我們運轉運用法式。假如一切順遂,這將打印以下信息:
------Records Creation-------- Created Record Name = Zara Age = 11 Created Record Name = Nuha Age = 2 Created Record Name = Ayan Age = 15 ------Listing Multiple Records-------- ID : 1, Name : Zara, Age : 11 ID : 2, Name : Nuha, Age : 2 ID : 3, Name : Ayan, Age : 15 ----Listing Record with ID = 2 ----- ID : 2, Name : Nuha, Age : 2