Spring JDBC入門程序
要了解JdbcTemplate類與Spring JDBC框架相關的概念,下面通過編寫一個簡單的例子演示如何使用Spring JDBC框架,在這個示例中,將在以student
表上實現插入數據和讀取數據的操作。
CREATE TABLE student(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
age INT NOT NULL,
PRIMARY KEY (id)
);
創建項目
首先打開Eclipse,創建一個Maven項目,選擇:File -> New -> Other… ,然後選擇:Maven Project 如下所示 -
下一步(Next>
),如下所示 -
填入項目的一些必要信息,如項目名稱,包的名稱等。
注意:第一個選項「Create a simple project(skip archetype selection)」選中。
這樣就創建好了一個名稱爲:firstapp 的java應用程序項目(在artifactId中指定)。更新pom.xml
以包含Spring-JDBC依賴關係。添加以下幾個類:Student.java
,StudentMapper.java
,MainApp.java
,StudentDAO.java
和StudentJDBCTemplate.java
等文件,完整的項目結構如下所示 -
文件 : pom.xml 的內容 -
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai</groupId>
<artifactId>fistapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Student</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>
以下是數據訪問對象接口文件: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);
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的代碼內容:
package com.yiibai;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
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 List<Student> listStudents() {
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
public Student getStudent(Integer id) {
// TODO Auto-generated method stub
return null;
}
}
以下是程序執行入口文件: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("application-beans.xml");
StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Maxsu", 19);
studentJDBCTemplate.create("Minsu", 23);
studentJDBCTemplate.create("Allen", 27);
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());
}
}
}
以下是Bean和數據庫配置文件:application-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="123456" />
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id="studentJDBCTemplate" class="com.yiibai.StudentJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
注意: application-beans.xml 文件的位置是:{workspace}/fistapp/src/main/java 目錄,如果放置錯了,程序可能會因爲找不到此配置文件而出錯。
完成創建源代碼和bean和數據庫連接信息的文件配置後,運行應用程序。這裏先簡單說明一下運行的步驟,在項目名稱(firstapp)上點擊右鍵,在彈出的菜單中選擇:【Run As】-> 【Maven test】,如下 -
在運行測試成功後,應該會輸出類似以下內容(含有 BUILD SUCCESS 的信息) -
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Student 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ fistapp ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ fistapp ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ fistapp ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ fistapp ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ fistapp ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.904 s
[INFO] Finished at: 2017-06-08T23:36:31+08:00
[INFO] Final Memory: 11M/114M
[INFO] ------------------------------------------------------------------------
接下來,點擊類文件:MainApp.java 選擇【Run As】->【Java Application】,如果應用程序一切正常,這將打印以下消息: