jdbctemplate 是在jdbc api基础上提供了更抽象的封装,并提供了基于方法注解的事务管理能力。 通过使用springboot自动配置功能并代替我们自动配置beans,下面给大家介绍spring boot中使用jdbctemplate相关知识,一起看看吧
本文将介绍如何将spring boot 与 jdbctemplate一起工作。
spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把datasource注册到jdbctemplate之中。 jdbctemplate 是在jdbc api基础上提供了更抽象的封装,并提供了基于方法注解的事务管理能力。 通过使用springboot自动配置功能并代替我们自动配置beans.
数据源配置
在maven中,我们需要增加spring-boot-starter-jdbc模块
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-jdbc</artifactid>
</dependency>
通过这个模块为我们做了以下几件事
tomcat-jdbc-{version}.jar为我们自动配置datasource.
如果你没有定义任何datasource,springboot将会自动配置一个内存的数据库资源设置
如果没有设置任一个beans,springboot会自动注册它
初始化数据库
如果我们在classpath里定义了schema.sql和data.sql文件,springboot将会使用这些文件自动初始化数据库(但你必须选建库)
除了载入schema.sql和data.sql外,springboot也会载入schema-${platform}.sql和data-${platform}.sql,如果在你的classpath下存在的话。
spring.datasource.schema=xxxx-db.sql 可以定义你的建库文件
spring.datasource.data=xxxx-data.sql 可以定义你的数据文件
spring.datasource.initialize=true|false 可以决定是不是要初始化这些数据库文件
spring.datasource.continueonerror=true|false 有了错误是否继续运行
嵌入式数据库支持
嵌入式数据库通常用于开发和测试环境,不推荐用于生产环境。spring boot提供自动配置的嵌入式数据库有h2、hsql、derby,你不需要提供任何连接配置就能使用。
比如,我们可以在pom.xml中引入如下配置使用hsql
<dependency>
<groupid>org.hsqldb</groupid>
<artifactid>hsqldb</artifactid>
<scope>runtime</scope>
</dependency>
连接生产数据源配置
以mysql数据库为例,先引入mysql连接的依赖包,在pom.xml中加入:
<dependency>
<groupid>mysql</groupid>
<artifactid>mysql-connector-java</artifactid>
<version>5.1.21</version>
</dependency>
在src/main/resources/application.properties中配置数据源信息
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.driver
连接jndi数据源配置
当你将应用部署于应用服务器上的时候想让数据源由应用服务器管理,那么可以使用如下配置方式引入jndi数据源。
spring.datasource.jndi-name=java:jboss/datasources/customers
自定义数据源配置
如果你不想用默认的配置数据源,如你想用阿里巴巴的数据池管理数据源,你也可以自己配置
先排除tomcat-jdbc的默认配置datasource
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-jdbc</artifactid>
<exclusions>
<exclusion>
<groupid>org.apache.tomcat</groupid>
<artifactid>tomcat-jdbc</artifactid>
</exclusion>
</exclusions>
</dependency>
定义自己的数据资源 这里使用了阿里巴巴的数据池管理,你也可以使用basicdatasource
<dependency>
<groupid>com.alibaba</groupid>
<artifactid>druid</artifactid>
<version>1.0.19</version>
</dependency>
package com.example;
import javax.sql.datasource;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.web.servlet.filterregistrationbean;
import org.springframework.boot.web.servlet.servletcomponentscan;
import org.springframework.boot.web.servlet.servletlistenerregistrationbean;
import org.springframework.boot.web.servlet.servletregistrationbean;
import org.springframework.context.annotation.bean;
import org.springframework.core.env.environment;
import org.springframework.web.servlet.dispatcherservlet;
import com.alibaba.druid.pool.druiddatasource;
import com.example.listener.indexlistener;
import com.example.filter.indexfilter;
import com.example.servlet.myservlet;
@springbootapplication
public class springbootsimpleapplication {
@autowired
private environment env;
@bean
public datasource datasource() {
druiddatasource datasource = new druiddatasource();
datasource.seturl(env.getproperty("spring.datasource.url"));
datasource.setusername(env.getproperty("spring.datasource.username"));//用户名
datasource.setpassword(env.getproperty("spring.datasource.password"));//密码
datasource.setdriverclassname(env.getproperty("spring.datasource.driver-class-name"));
datasource.setinitialsize(2);
datasource.setmaxactive(20);
datasource.setminidle(0);
datasource.setmaxwait(60000);
datasource.setvalidationquery("select 1");
datasource.settestonborrow(false);
datasource.settestwhileidle(true);
datasource.setpoolpreparedstatements(false);
return datasource;
}
public static void main(string[] args) {
springapplication.run(springbootsimpleapplication.class, args);
}
}
你也可以用别的:
<dependency>
<groupid>commons-dbcp</groupid>
<artifactid>commons-dbcp</artifactid>
<version>1.4</version>
</dependency>
@bean
public datasource datasource() {
basicdatasource datasource = new basicdatasource();
datasource.setdriverclassname(env.getproperty("spring.datasource.driver-class-name"));
datasource.seturl(env.getproperty("spring.datasource.url"));
datasource.setusername(env.getproperty("spring.datasource.username"));
datasource.setpassword(env.getproperty("spring.datasource.password"));
return datasource;
}
代码示例
创建实体对象
/src/main/java/com/example/domain/user.java
package com.example.domain;
public class user
{
private integer id;
private string name;
private string email;
public user()
{
}
public user(integer id, string name, string email)
{
this.id = id;
this.name = name;
this.email = email;
}
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 getemail()
{
return email;
}
public void setemail(string email)
{
this.email = email;
}
@override
public string tostring() {
return "user{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
创建持久层
有了上面的数据源配置,我们可以注入jdbctemplate到数据访问组件并与数据库交互。
/src/main/java/com/example/repositories/userrepository.java
package com.example.repositories;
import com.example.domain.user;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.jdbc.core.jdbctemplate;
import org.springframework.jdbc.core.preparedstatementcreator;
import org.springframework.jdbc.core.rowmapper;
import org.springframework.jdbc.support.generatedkeyholder;
import org.springframework.jdbc.support.keyholder;
import org.springframework.stereotype.repository;
import org.springframework.transaction.annotation.transactional;
import java.sql.*;
import java.util.list;
@repository
public class userrepository {
@autowired
private jdbctemplate jdbctemplate;
@transactional(readonly = true)
public list<user> findall() {
return jdbctemplate.query("select * from users", new userrowmapper());
}
@transactional(readonly = true)
public user finduserbyid(int id) {
return jdbctemplate.queryforobject("select * from users where id=?", new object[]{id}, new userrowmapper());
}
public user create(final user user) {
final string sql = "insert into users(name,email) values(?,?)";
keyholder holder = new generatedkeyholder();
jdbctemplate.update(new preparedstatementcreator() {
@override
public preparedstatement createpreparedstatement(connection connection)
throws sqlexception {
preparedstatement ps = connection.preparestatement(sql, statement.return_generated_keys);
ps.setstring(1, user.getname());
ps.setstring(2, user.getemail());
return ps;
}
}, holder);
int newuserid = holder.getkey().intvalue();
user.setid(newuserid);
return user;
}
public void delete(final integer id) {
final string sql = "delete from users where id=?";
jdbctemplate.update(sql,
new object[]{id},
new int[]{java.sql.types.integer});
}
public void update(final user user) {
jdbctemplate.update(
"update users set name=?,email=? where id=?",
new object[]{user.getname(), user.getemail(), user.getid()});
}
}
class userrowmapper implements rowmapper<user> {
@override
public user maprow(resultset rs, int rownum) throws sqlexception {
user user = new user();
user.setid(rs.getint("id"));
user.setname(rs.getstring("name"));
user.setemail(rs.getstring("email"));
return user;
}
}
单元测试
你或许己注意到,大多数时候,我们都在应用中做这些配置的事。
创建单元测试测试我们的持久层方法
/src/test/java/springbootjdbcdemoapplicationtests.java
import com.example.springbootjdbcdemoapplication;
import com.example.domain.user;
import com.example.repositories.userrepository;
import org.junit.test;
import org.junit.runner.runwith;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.springapplicationconfiguration;
import org.springframework.test.context.junit4.springjunit4classrunner;
import java.util.list;
import static org.junit.assert.*;
import static org.junit.assert.assertequals;
@runwith(springjunit4classrunner.class)
@springapplicationconfiguration(springbootjdbcdemoapplication.class)
public class springbootjdbcdemoapplicationtests
{
logger logger= loggerfactory.getlogger(springbootjdbcdemoapplicationtests.class);
@autowired
private userrepository userrepository;
@test public void testall(){
findallusers();
finduserbyid();
createuser();
}
@test
public void findallusers() {
list<user> users = userrepository.findall();
assertnotnull(users);
asserttrue(!users.isempty());
}
@test
public void finduserbyid() {
user user = userrepository.finduserbyid(1);
assertnotnull(user);
}
private void updatebyid(integer id) {
user newuser = new user(id, "jackchen", "jackchen@qq.com");
userrepository.update(newuser);
user newuser2 = userrepository.finduserbyid(newuser.getid());
assertequals(newuser.getname(), newuser2.getname());
assertequals(newuser.getemail(), newuser2.getemail());
}
@test
public void createuser() {
user user = new user(0, "tom", "tom@gmail.com");
user saveduser = userrepository.create(user);
logger.debug("{}",saveduser);
user newuser = userrepository.finduserbyid(saveduser.getid());
assertequals("tom", newuser.getname());
assertequals("tom@gmail.com", newuser.getemail());
updatebyid(newuser.getid());
userrepository.delete(newuser.getid());
}
}
【相关推荐】
1. java免费视频教程
2. 全面解析java注解
3. 阿里巴巴java开发手册
以上就是关于jdbctemplate使用的实例详解的详细内容。