码迷,mamicode.com
首页 > 数据库 > 详细

Spring(十)Spring JDBCTemplate

时间:2018-03-17 10:48:27      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:.sql   公司   模板类   dep   1.0   www   xmlns   nbsp   nts   

JdbcTemplate是Spring提供的一个请有力的模板类,他简化了JDBC的操作,DateSource对象与末班JdbcTemplate对象均可以通过Bean的形式定义在配置文件中,充分发挥了依赖注入的威力!!!下面通过一个例子来使用一下JdbcTemplate

案例:查询所有图书

首先创建数据表

技术分享图片

开始编写代码:

第一步:引入jar  Spring-jdbc,引入这个jar之后会引带这将事务的包也引进来

技术分享图片
<!--jdbc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>
技术分享图片

第二步:创建实体类Book在entity包下

技术分享图片
package demoJDBC.entity;

/**
 * Created by mycom on 2018/1/29.
 */
public class Book {
    private Integer bookID;
    private String  bookName;
    private String bookAuthor;
    private Integer bookPrice;

    @Override
    public String toString() {
        return "Book{" +
                "bookID=" + bookID +
                ", bookName=‘" + bookName + ‘\‘‘ +
                ", bookAuthor=‘" + bookAuthor + ‘\‘‘ +
                ", bookPrice=" + bookPrice +
                ‘}‘;
    }

    public Integer getBookID() {
        return bookID;
    }

    public void setBookID(Integer bookID) {
        this.bookID = bookID;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getBookAuthor() {
        return bookAuthor;
    }

    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }

    public Integer getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(Integer bookPrice) {
        this.bookPrice = bookPrice;
    }
}
技术分享图片

第三步:创建Dao层

接口:

技术分享图片
package demoJDBC.dao;

import demoJDBC.entity.Book;

import java.util.List;

/**
 * Created by mycom on 2018/3/12.
 */
public interface IBookDao {
    public List<Book> findAll();

}
技术分享图片

Dao实现类

技术分享图片
package demoJDBC.dao;


import demoJDBC.entity.Book;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by mycom on 2018/3/12.
 */
public class BookDaoImpl extends JdbcDaoSupport implements IBookDao {
    public List<Book> findAll() {
        //sql
        String sql="select * from book";
        List<Book> list = this.getJdbcTemplate().query(sql, new RowMapper<Book>() {
            public Book mapRow(ResultSet rs, int i) throws SQLException {
                //创建一个Book对象
                Book book = new Book();
                book.setBookID(rs.getInt("bookID"));
                book.setBookName(rs.getString("bookName"));
/*                book.setBookAuthor(rs.getString("bookAuthor"));
                book.setBookPrice(rs.getInt("bookPrice"));*/
                return book;
            }
        });
        return list;
    }
}
技术分享图片

第四步:创建service层

接口:

技术分享图片
package demoJDBC.service;

import demoJDBC.entity.Book;

import java.util.List;

/**
 * Created by mycom on 2018/3/13.
 */
public interface IBookService {
    public List<Book> findAll();
}
技术分享图片

接口的实现类

技术分享图片
package demoJDBC.service;

import demoJDBC.dao.BookDaoImpl;
import demoJDBC.entity.Book;

import java.util.List;

/**
 * Created by mycom on 2018/3/13.
 */
public class BookServiceImpl implements IBookService {
    BookDaoImpl book;

    public BookDaoImpl getBook() {
        return book;
    }

    public void setBook(BookDaoImpl book) {
        this.book = book;
    }

    public List<Book> findAll() {
        return book.findAll();
    }
}
技术分享图片

第五步:在resources下创建jdbc.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///book
jdbc.username=root
jdbc.password=

第六步:配置xml文件applicationContextJDBCTemplate.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" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置数据源-->
    <!--配置1-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--&lt;!&ndash;配置2&ndash;&gt;
    <bean id="dateSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>-->
    <!--&lt;!&ndash;配置3&ndash;&gt;
    <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>-->
    <!--配置4-->
    <!--<bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>-->

    <!--识别到jdbc.properties-->
    <!--配置1-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--配置2-->
    <!--<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>-->
    <!--配置jdbcTemeplate-->
    <bean id="jdbcTemeplate1" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>
    <!--配置Dao-->
    <bean id="bookDao" class="demoJDBC.dao.BookDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemeplate1"></property>
    </bean>
    <!--service id-->
    <bean id="bookService" class="demoJDBC.service.BookServiceImpl">
        <property name="book" ref="bookDao"></property>
    </bean>
</beans>
技术分享图片

配置文件中配置数据源的方法有四种,配置JDBC的文件的有两种,下面我在提出来分别写一下

(1)配置数据源

  1)Spring内置的  DriverManagerDataSource(很少用)

<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

  2)DBCP 它时apache下的(公司比较常用),这种方式需要引入jar

技术分享图片
<!--dbcp2-->
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>

或者是

<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>

 

版本问题的话就自己更换版本吧

技术分享图片
<bean id="dateSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

  3)c3p0 (公司比较常用),这种方式需要引入jar

技术分享图片
<!--c3p0-->
        <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
技术分享图片
<bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

  4)阿里巴巴的 druid

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
<bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

(2)配置JDBC的两种方法

<!--配置2-->
    <!--<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"></property>
    </bean>-->
    <!--识别到jdbc.properties-->
    <!--配置1-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

最后一步:编写测试方法

技术分享图片
import demo03.ISomeService;
import demoJDBC.entity.Book;
import demoJDBC.service.IBookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * Created by mycom on 2018/3/11.
 */
public class TestDemoJDBC {

    @Test
    public void t1(){
        //获取对象
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContextJDBCTemplate.xml");
        //调用方法,这里要返回类
        IBookService bookService =(IBookService) context.getBean("bookService");
        List<Book> all = bookService.findAll();
        for (Book book:all) {
            System.out.println(book.getBookName());
        }
    }
}

Spring(十)Spring JDBCTemplate

标签:.sql   公司   模板类   dep   1.0   www   xmlns   nbsp   nts   

原文地址:https://www.cnblogs.com/a157/p/8587174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!