JAVA入門[19]-JdbcTemplate簡單一實例,java-jdbctemplate

來源:互聯網
上載者:User

JAVA入門[19]-JdbcTemplate簡單一實例,java-jdbctemplate
一、關於JdbcTemplate

JdbcTemplate是最基本的Spring JDBC模板,這個模板支援簡單的JDBC資料庫訪問功能以及基於索引參數的查詢。

Spring資料訪問模板:在資料庫操作過程中,有很大一部分重複工作,比如事務控制、管理資源以及處理異常等,Spring的模板類處理這些固定部分。同時,應用程式相關的資料訪問在回調的實現中處理,包括語句、綁定參數以及整理結果等。這樣一來,我們只需關心自己的資料訪問邏輯即可。

二、Spring JdbcTemplate執行個體

我們的學習目標就是動手寫一個demo,實現對Category的CRUD操作。

1.建立表

mysql建立資料庫store,然後執行如下sql:

create table Category (Id int not null,Name varchar(80) null,constraint pk_category primary key (Id));INSERT INTO category(id,Name) VALUES (1,'女裝');INSERT INTO category(id,Name) VALUES (2,'美妝');INSERT INTO category(id,Name) VALUES (3,'書籍');db_store.sql

2.我用的IDE是IdeaIU,通過maven構建項目,通過xml配置spring。完成後的代碼結構為:

public class Category{ private int cateId; private String cateName; public int getCateId() { return cateId; } public void setCateId(int cateId) { this.cateId = cateId; } public String getCateName() { return cateName; } public void setCateName(String cateName) { this.cateName = cateName; } @Override public String toString() { return "id="+cateId+" name="+cateName; }}

  

4.修改pom.xml,引入相關依賴。

    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.12</version>        </dependency>        <!-- Mysql資料庫連結jar包 -->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.21</version>            <scope>runtime</scope>        </dependency>    </dependencies>

  

5.配置applicationContext.xml

需要配置dataSource作為jdbcTemplate的資料來源。然後配置CategoryDao bean,構造注入了jdbcTemplate對象。完整的applicationContext.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.xsd">    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>        <property name="url" value="jdbc:mysql://localhost:3306/store"></property>        <property name="username" value="root"></property>        <property name="password" value="root"></property>    </bean>    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <property name="dataSource" ref="dataSource"></property>    </bean>        <bean id="categoryDao" class="CategoryDao">        <constructor-arg ref="jdbcTemplate"></constructor-arg>    </bean></beans>

  

6.資料訪問實作類別CategoryDao

CategoryDao建構函式包含了參數jdbcTemplate,然後實現了常用的資料訪問操作。可以看到,我們只要關注具體的sql語句就可以了。另外,在getById()和getAll()方法中使用了lambda文法。

import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import java.util.Map;/** * Created by 陳敬 on 2017/6/6. */public class CategoryDao {    private JdbcTemplate jdbcTemplate;    public CategoryDao(JdbcTemplate jdbcTemplate) {        this.jdbcTemplate = jdbcTemplate;    }    public int add(Category category) {        String sql = "INSERT INTO category(id,name)VALUES(?,?)";        return jdbcTemplate.update(sql, category.getCateId(), category.getCateName());    }    public int update(Category category) {        String sql = "UPDATE Category SET Name=? WHERE Id=?";        return jdbcTemplate.update(sql, category.getCateName(), category.getCateId());    }    public int delete(int id) {        String sql = "DELETE FROM Category WHERE Id=?";        return jdbcTemplate.update(sql, id);    }    public int count(){        String sql="SELECT COUNT(0) FROM Category";        return jdbcTemplate.queryForObject(sql,Integer.class);    }    public Category getById(int id) {        String sql = "SELECT Id,Name FROM Category WHERE Id=?";        return jdbcTemplate.queryForObject(sql, (ResultSet rs, int rowNumber) -> {            Category category = new Category();            category.setCateId(rs.getInt("Id"));            category.setCateName(rs.getString("Name"));            return category;        }, id);    }    public List<Category> getAll(){        String sql="SELECT Id,Name FROM Category";        List<Category> result=jdbcTemplate.query(sql, (resultSet, i) -> {            Category category = new Category();            category.setCateId(resultSet.getInt("Id"));            category.setCateName(resultSet.getString("Name"));            return category;        });        return result;    }}

  

7.測試

@ContextConfiguration(locations = "classpath:applicationContext.xml")@RunWith(SpringJUnit4ClassRunner.class)public class testCategoryDao {    @Autowired    private CategoryDao categoryDao;    @Test    public void testAdd() {        Category category = new Category();        category.setCateId(4);        category.setCateName("母嬰");        int result = categoryDao.add(category);        System.out.println(result);    }    @Test    public void testUpdate() {        Category category = new Category();        category.setCateId(4);        category.setCateName("男裝");        int result = categoryDao.update(category);        System.out.println(result);    }    @Test    public void testGetById() {        int id = 4;        Category category = categoryDao.getById(id);        System.out.println(category.toString());    }    @Test    public void testGetAll() {        List<Category> categories = categoryDao.getAll();        for (Category item : categories) {            System.out.println(item);        }    }    @Test    public void testCount() {        int count = categoryDao.count();        System.out.println(count);    }    @Test    public void testDelete() {        int id = 4;        int result = categoryDao.delete(id);        System.out.println(result);    }}

  

完整代碼:https://github.com/cathychen00/learnjava/tree/master/DemoJdbcTemplate

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.