当前位置: 移动技术网 > IT编程>开发语言>Java > 浅析Spring的JdbcTemplate方法

浅析Spring的JdbcTemplate方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

spring对于数据访问层提供了多种的模板技术。如果直接使用jdbc,那么可以选择jdbctemplate、如果使用的是对象关系映射框架,使用hibernate应该使用hibernatetemplate模板,使用jpa则应该使用jpatemplate。

除此之外,spring框架为每一项的持久层技术都提供了相应的帮助类来简化操作。对于jdbc提供了jdbcdaosupport类、对于hibernate技术提供了hibernatedaosupport类、对于mybatis提供了sqlmapclientdaosupport类。

本篇主要介绍spring如何使用jdbctemplate来访问关系型数据库。

1.首先引入使用spring的jdbc模块时的jar文件(maven项目可引入对应的依赖)。

  • spring-beans-3.2.0.release.jar
  • spring-context-3.2.0.release.jar
  • spring-core-3.2.0.release.jar
  • spring-expression-3.2.0.release.jar
  • commons-logging-1.2.jar
  • spring-jdbc-3.2.0.release.jar
  • spring-tx-3.2.0.release.jar

对应的数据库驱动(这里采用mysql)

2.在src下引入两个文件:applicationcontext.xml和log4j.xml

3.下面以连接两种数据库连接池的技术来介绍spring关于jdbctemplate的使用:

使用spring内置的数据库连接池:

drivermanagerdatasource datasource=new drivermanagerdatasource();
    datasource.setdriverclassname("com.mysql.jdbc.driver");
    datasource.seturl("jdbc:mysql:///springjdbc");
    datasource.setusername("root");
    datasource.setpassword("1997wfy.....");

    jdbctemplate template=new jdbctemplate();
    template.setdatasource(datasource);
    template.execute("create table book(id int primary key auto_increment,name varchar(20) not null,author varchar(25))");

或者:

  <!-- xml配置spring默认的连接池 -->
  <bean id="drivermanagerdatasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource">
    <property name="driverclassname" value="com.mysql.jdbc.driver"/>
    <property name="url" value="jdbc:mysql:///springjdbc"/> 
    <property name="username" value="root"/>
    <property name="password" value="1997wfy....."/>
  </bean>
  <bean class="org.springframework.jdbc.core.jdbctemplate">
    <property name="datasource" ref="drivermanagerdatasource"/>
  </bean>

java代码使用:

/**
 * @author beautifulsoup
 * 首先使用spring内置的连接池
 */
@contextconfiguration("classpath:applicationcontext.xml")
@runwith(springjunit4classrunner.class)
public class springjdbctest {

  @autowired
  private jdbctemplate template;

  @test
  public void testdrivermanagerdatasource() {
    template.execute("create table book(id int primary key auto_increment,name varchar(20) not null,author varchar(25))");
  }

}

使用世界上性能最好的druid连接池:

  <!-- 配置druid的连接池 -->
  <bean id="druiddatasource" class="com.alibaba.druid.pool.druiddatasource">
    <property name="driverclassname" value="com.mysql.jdbc.driver" />
    <property name="url" value="jdbc:mysql:///springjdbc" />
    <property name="username" value="root" />
    <property name="password" value="1997wfy....." />
    <!-- 设置初始的连接数目,最小的连接数,最大的连接数 -->
    <property name="initialsize" value="1" />
    <property name="minidle" value="1" />
    <property name="maxactive" value="8" />
    <!-- 配置获取连接等待超时的时间 -->
    <property name="maxwait" value="10000" />
    <!-- 配置间隔多久才进行一次检测需要关闭的空闲连接 -->
    <property name="timebetweenevictionrunsmillis" value="60000" />
    <!-- 配置一个连接在池中最小的生存时间 -->
    <property name="minevictableidletimemillis" value="300000" />
    <property name="testwhileidle" value="true" />
    <!-- 这里建议配置为true,防止取到的连接不可用 -->
    <property name="testonborrow" value="true" />
    <property name="testonreturn" value="false" />
    <!-- 打开pscache,并且指定每个连接上pscache的大小 -->
    <property name="poolpreparedstatements" value="true" />
    <property name="maxpoolpreparedstatementperconnectionsize"
      value="20" />
    <!-- 这里配置提交方式,默认就是true,可以不用配置 -->
    <property name="defaultautocommit" value="true" />
    <!-- 验证连接有效与否的sql,不同的数据配置不同 -->
    <property name="validationquery" value="select 1 " />
    <property name="filters" value="stat" />
  </bean>
  <bean class="org.springframework.jdbc.core.jdbctemplate">
    <property name="datasource" ref="druiddatasource" />
  </bean>

/**
 * @author beautifulsoup
 * 首先使用spring内置的连接池
 */
@contextconfiguration("classpath:applicationcontext.xml")
@runwith(springjunit4classrunner.class)
public class springjdbctest {
  @autowired
  private jdbctemplate template;
  @test
  public void testspringjdbc() {
    template.execute("create table book(id int primary key auto_increment,name varchar(20) not null,author varchar(25))");
  }
}

4.使用得到的jdbctemplate进行基本的增删改查:

首先创建实体类对象,

/**
 * @author beautifulsoup
 * 创建实体类对象
 */
public class book {
  private integer id;
  private string name;
  private string author;
  public integer getid() {
    return id;
  }
  public void setid(integer id) {
    this.id = id;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public string getauthor() {
    return author;
  }
  public void setauthor(string author) {
    this.author = author;
  }
  @override
  public string tostring() {
    return "book [id=" + id + ", name=" + name + ", author=" + author + "]";
  }
}

在配置文件中配置bean:

<bean class="com.fuyunwang.springjdbc.dao.bookdao">
    <property name="jdbctemplate" ref="jdbctemplate"/>
</bean>

dao层进行持久层的开发:

/**
 * @author beautifulsoup 完成基本的增删改查
 */
public class bookdao extends jdbcdaosupport {

  public void add(book book) {
    string sql = "insert into book values(?,?,?)";
    getjdbctemplate().update(sql, book.getid(), book.getname(),
        book.getauthor());
  }

  public void update(book book) {
    string sql = "update book set name = ? , author = ? where id =?";
    getjdbctemplate().update(sql, book.getname(), book.getauthor(),
        book.getid());
  }

  public void delete(book book) {
    string sql = "delete from book where id =?";
    getjdbctemplate().update(sql, book.getid());
  }

  public int findcount() {
    string sql = "select count(*) from book";
    return getjdbctemplate().queryforint(sql);
  }

  public string findnamebyid(int id) {
    string sql = "select name from book where id = ?";
    return getjdbctemplate().queryforobject(sql, string.class, id);
  }

  public book findbyid(int id) {
    string sql = "select * from book where id = ?";
    return getjdbctemplate().queryforobject(sql, new bookmapper(), id);
  }

  public list<book> findall(){
    string sql="select * from book";
    return getjdbctemplate().query(sql, new bookmapper());
  }
  class bookmapper implements rowmapper<book> {
    public book maprow(resultset rs, int rownum) throws sqlexception {
      book book = new book();
      book.setid(rs.getint("id"));
      book.setname(rs.getstring("name"));
      book.setauthor(rs.getstring("author"));
      return book;
    }

  }
}

单元测试,

/**
 * @author beautifulsoup
 * 首先使用spring内置的连接池
 */
@runwith(springjunit4classrunner.class)
@contextconfiguration("classpath:applicationcontext.xml")
public class springjdbctest {

  @autowired
  private bookdao bookdao;

  @test
  public void jdbctemplateadd(){
    book book=new book();
    book.setid(1);
    book.setname("springboot实战");
    book.setauthor("craig walls");
    bookdao.add(book);
  }


}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网