歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring應用——對 JDBC 的支持

Spring應用——對 JDBC 的支持

日期:2017/3/1 9:13:30   编辑:Linux編程

一、說明

1.Spring JDBC 對原始的 JDBC 進行了封裝,使其更加易用。

2.JdbcTemplate 作為 Spring JDBC 的核心,為不同類型的 JDBC 操作提供了模板方法。

3.JdbcTemplate 對於 Spring 作用與 DbUtils 對於 Jdbc 的意義相同。它們做的是同一件事情。

二、JdbcTemplate

1.在 Spring Config 文件中注冊 JdbcTemplate 的實例,同時配置數據源,如:

<context:property-placeholder location="classpath:db.properties"/>

<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
  <property name="driverClass" value="${jdbc.driverClass}"/>
  <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
  <property name="user" value="${jdbc.user}"/>
  <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property name="dataSource" ref="dataSource"/>
</bean>

2.在目標類中,注入 JdbcTemplate 實例,進行相應的 Jdbc 操作。

/**
 * @author solverpeng
 * @create 2016-07-28-20:29
 */
@Repository
public class StudentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

3.更新(增、刪、改)和批量更新,這裡只作一個類型的例子。

(1)增,返回受影響的行數

StudentDao:

public void insertStudent() {
  String sql = "insert into student(student_id, student_name, student_class) " +
      "values(?,?,?)";
  int affectRows = this.jdbcTemplate.update(sql, 1, "tom", "0102");
  System.out.println("affectRows:" + affectRows);
}

控制台輸出:

affectRows:1

(2)增,返回增加的主鍵值

StudentDao:

public void insertStudent2() {
  PreparedStatementCreator psc = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
      String sql = "insert into student(student_id, student_name, student_class) values(?, ?, ?)";
      PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
      ps.setInt(1, 2);
      ps.setString(2, "jerry");
      ps.setString(3, "0805");
      return ps;
    }
  };
  KeyHolder keyHolder = new GeneratedKeyHolder();
  this.jdbcTemplate.update(psc, keyHolder);
  Number key = keyHolder.getKey();
  System.out.println(key);
}

數據庫:

控制台輸出:

2

在做這個測試的時候遇到一個問題:!Statement.GeneratedKeysNotRequested!

解決:http://stackoverflow.com/questions/7162989/sqlexception-generated-keys-not-requested-mysql

(3)批量增

StudentDao:

public vod batchUpdate() {
  String sql = "insert into student(student_id, student_name, student_class) values(?, ?, ?)";
  List<Object[]> list = new ArrayList<>();
  list.add(new Object[]{3, "lily", "0806"});
  list.add(new Object[]{4, "lucy", "0807"});
  this.jdbcTemplate.batchUpdate(sql, list);
}

數據庫:

4.查詢單個對象:queryForObject

StudentDao:

public void getStudent(Integer id) {
  String sql = "select student_id, student_name, student_class from student where student_id = ?";
  RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
  Student student = this.jdbcTemplate.queryForObject(sql, rowMapper, id);
  System.out.println(student);
}

控制台輸出:

Student{studentId=1, studentName='tom', studentClass='0804'}

5.返回查詢的記錄數

public void getCount() {
  String sql = "select count(student_id) from student";
  Long count = this.jdbcTemplate.queryForObject(sql, Long.class);
  System.out.println(count);
}

控制台輸出:

4

三、NamedParameterJdbcTemplate :在 sql 中嵌入命名參數。

1.同樣在 Spring Config 文件中進行配置

2.使用 ParamMap 插入

StudentDao:

public void insert() {
  String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
  Map<String, Object> paramMap = new HashMap<>();
  paramMap.put("studentId", 5);
  paramMap.put("studentName", "jakc");
  paramMap.put("studentClass", "0808");
  this.namedParameterJdbcTemplate.update(sql, paramMap);
}

數據庫:

3.使用 SqlParameterSource 插入

public void insert2() {
  String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
  Student student = new Student();
  student.setStudentId(6);
  student.setStudentName("mary");
  student.setStudentClass("0809");
  SqlParameterSource source = new BeanPropertySqlParameterSource(student);
  this.namedParameterJdbcTemplate.update(sql, source);
}

數據庫:

4.使用 SqlParameterSource 插入返回主鍵

public void insert3() {
  String sql = "insert into student(student_id, student_name, student_class) values(:studentId, :studentName, :studentClass)";
  Student student = new Student();
  student.setStudentId(7);
  student.setStudentName("kobe");
  student.setStudentClass("0810");
  SqlParameterSource source = new BeanPropertySqlParameterSource(student);
  KeyHolder keyHolder = new GeneratedKeyHolder();
  this.namedParameterJdbcTemplate.update(sql,source, keyHolder);
  Number key = keyHolder.getKey();
  System.out.println(key);
}

控制台輸出:

7

數據庫:

四、繼承 JdbcDaoSupport

1.繼承 JdbcDaoSupport,需要為每一個目標類配置數據源,JdbcTemplate會自動注入,不需要在SpringConfig文件中配置JdbcTemplate。

2.需要注意的是,不能在目標類中通過 @Autowired 的方式注入 dataSource。

3.演示一個例子:

/**
 * @author solverpeng
 * @create 2016-07-29-11:29
 */
@Repository
public class PersonDao extends JdbcDaoSupport{
    public void insert() {
        String sql = "insert into person(id, person_name) values(?, ?)";
        this.getJdbcTemplate().update(sql, 1, "tom");
    }
}

SpringConfig文件:

<bean class="com.nucsoft.spring.jdbc.PersonDao" id="dao">
    <property name="dataSource" ref="dataSource"/>
</bean>

Spring中如何配置Hibernate事務 http://www.linuxidc.com/Linux/2013-12/93681.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基於 Spring 設計並實現 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成實例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 進行單元測試 http://www.linuxidc.com/Linux/2013-09/89913.htm

運用Spring注解實現Netty服務器端UDP應用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企業應用開發實戰 PDF完整高清掃描版+源代碼 http://www.linuxidc.com/Linux/2013-10/91357.htm

Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved