详解spring boot中使用JdbcTemplate
本文将介绍如何将springboot与JdbcTemplate一起工作。
Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。JdbcTemplate是在JDBCAPI基础上提供了更抽象的封装,并提供了基于方法注解的事务管理能力。通过使用SpringBoot自动配置功能并代替我们自动配置beans.
数据源配置
在maven中,我们需要增加spring-boot-starter-jdbc模块
org.springframework.boot spring-boot-starter-jdbc
通过这个模块为我们做了以下几件事
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有了错误是否继续运行
嵌入式数据库支持
嵌入式数据库通常用于开发和测试环境,不推荐用于生产环境。SpringBoot提供自动配置的嵌入式数据库有H2、HSQL、Derby,你不需要提供任何连接配置就能使用。
比如,我们可以在pom.xml中引入如下配置使用HSQL
org.hsqldb hsqldb runtime
连接生产数据源配置
以MySQL数据库为例,先引入MySQL连接的依赖包,在pom.xml中加入:
mysql mysql-connector-java 5.1.21
在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
org.springframework.boot spring-boot-starter-jdbc org.apache.tomcat tomcat-jdbc
定义自己的数据资源这里使用了阿里巴巴的数据池管理,你也可以使用BasicDataSource
com.alibaba druid 1.0.19
packagecom.example;
importjavax.sql.DataSource;
importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.boot.web.servlet.FilterRegistrationBean; importorg.springframework.boot.web.servlet.ServletComponentScan; importorg.springframework.boot.web.servlet.ServletListenerRegistrationBean; importorg.springframework.boot.web.servlet.ServletRegistrationBean; importorg.springframework.context.annotation.Bean; importorg.springframework.core.env.Environment; importorg.springframework.web.servlet.DispatcherServlet; importcom.alibaba.druid.pool.DruidDataSource; importcom.example.Listener.IndexListener; importcom.example.filter.IndexFilter; importcom.example.servlet.MyServlet; @SpringBootApplication publicclassSpringBootSimpleApplication{ @Autowired privateEnvironmentenv; @Bean publicDataSourcedataSource(){ DruidDataSourcedataSource=newDruidDataSource(); 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("SELECT1"); dataSource.setTestOnBorrow(false); dataSource.setTestWhileIdle(true); dataSource.setPoolPreparedStatements(false); returndataSource; } publicstaticvoidmain(String[]args){ SpringApplication.run(SpringBootSimpleApplication.class,args); } }
你也可以用别的:
@Bean publicDataSourcedataSource(){ BasicDataSourcedataSource=newBasicDataSource(); 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")); returndataSource; } commons-dbcp commons-dbcp 1.4
代码示例
创建实体对象
/src/main/java/com/example/domain/User.java
packagecom.example.domain; publicclassUser { privateIntegerid; privateStringname; privateStringemail; publicUser() { } publicUser(Integerid,Stringname,Stringemail) { this.id=id; this.name=name; this.email=email; } publicIntegergetId() { returnid; } publicvoidsetId(Integerid) { this.id=id; } publicStringgetName() { returnname; } publicvoidsetName(Stringname) { this.name=name; } publicStringgetEmail() { returnemail; } publicvoidsetEmail(Stringemail) { this.email=email; } @Override publicStringtoString(){ return"User{"+ "id="+id+ ",name='"+name+'\''+ ",email='"+email+'\''+ '}'; } }
创建持久层
有了上面的数据源配置,我们可以注入JdbcTemplate到数据访问组件并与数据库交互。
/src/main/java/com/example/repositories/UserRepository.java
packagecom.example.repositories; importcom.example.domain.User; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.jdbc.core.JdbcTemplate; importorg.springframework.jdbc.core.PreparedStatementCreator; importorg.springframework.jdbc.core.RowMapper; importorg.springframework.jdbc.support.GeneratedKeyHolder; importorg.springframework.jdbc.support.KeyHolder; importorg.springframework.stereotype.Repository; importorg.springframework.transaction.annotation.Transactional; importjava.sql.*; importjava.util.List; @Repository publicclassUserRepository{ @Autowired privateJdbcTemplatejdbcTemplate; @Transactional(readOnly=true) publicListfindAll(){ returnjdbcTemplate.query("select*fromusers",newUserRowMapper()); } @Transactional(readOnly=true) publicUserfindUserById(intid){ returnjdbcTemplate.queryForObject("select*fromuserswhereid=?",newObject[]{id},newUserRowMapper()); } publicUsercreate(finalUseruser){ finalStringsql="insertintousers(name,email)values(?,?)"; KeyHolderholder=newGeneratedKeyHolder(); jdbcTemplate.update(newPreparedStatementCreator(){ @Override publicPreparedStatementcreatePreparedStatement(Connectionconnection) throwsSQLException{ PreparedStatementps=connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); ps.setString(1,user.getName()); ps.setString(2,user.getEmail()); returnps; } },holder); intnewUserId=holder.getKey().intValue(); user.setId(newUserId); returnuser; } publicvoiddelete(finalIntegerid){ finalStringsql="deletefromuserswhereid=?"; jdbcTemplate.update(sql, newObject[]{id}, newint[]{java.sql.Types.INTEGER}); } publicvoidupdate(finalUseruser){ jdbcTemplate.update( "updateuserssetname=?,email=?whereid=?", newObject[]{user.getName(),user.getEmail(),user.getId()}); } } classUserRowMapperimplementsRowMapper { @Override publicUsermapRow(ResultSetrs,introwNum)throwsSQLException{ Useruser=newUser(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setEmail(rs.getString("email")); returnuser; } }
单元测试
你或许己注意到,大多数时候,我们都在应用中做这些配置的事。
创建单元测试测试我们的持久层方法
/src/test/java/SpringBootJdbcDemoApplicationTests.java
importcom.example.SpringBootJdbcDemoApplication; importcom.example.domain.User; importcom.example.repositories.UserRepository; importorg.junit.Test; importorg.junit.runner.RunWith; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.boot.test.SpringApplicationConfiguration; importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner; importjava.util.List; importstaticorg.junit.Assert.*; importstaticorg.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SpringBootJdbcDemoApplication.class) publicclassSpringBootJdbcDemoApplicationTests { Loggerlogger=LoggerFactory.getLogger(SpringBootJdbcDemoApplicationTests.class); @Autowired privateUserRepositoryuserRepository; @TestpublicvoidtestAll(){ findAllUsers(); findUserById(); createUser(); } @Test publicvoidfindAllUsers(){ Listusers=userRepository.findAll(); assertNotNull(users); assertTrue(!users.isEmpty()); } @Test publicvoidfindUserById(){ Useruser=userRepository.findUserById(1); assertNotNull(user); } privatevoidupdateById(Integerid){ UsernewUser=newUser(id,"JackChen","JackChen@qq.com"); userRepository.update(newUser); UsernewUser2=userRepository.findUserById(newUser.getId()); assertEquals(newUser.getName(),newUser2.getName()); assertEquals(newUser.getEmail(),newUser2.getEmail()); } @Test publicvoidcreateUser(){ Useruser=newUser(0,"tom","tom@gmail.com"); UsersavedUser=userRepository.create(user); logger.debug("{}",savedUser); UsernewUser=userRepository.findUserById(savedUser.getId()); assertEquals("tom",newUser.getName()); assertEquals("tom@gmail.com",newUser.getEmail()); updateById(newUser.getId()); userRepository.delete(newUser.getId()); } }
以上所述是小编给大家介绍的springboot中使用JdbcTemplate,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!