最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解spring boot中使用JdbcTemplate

 更新時(shí)間:2017年04月24日 15:05:16   作者:牛頭人  
JdbcTemplate 是在JDBC API基礎(chǔ)上提供了更抽象的封裝,并提供了基于方法注解的事務(wù)管理能力。 通過使用SpringBoot自動(dòng)配置功能并代替我們自動(dòng)配置beans,下面給大家介紹spring boot中使用JdbcTemplate相關(guān)知識(shí),一起看看吧

本文將介紹如何將spring boot 與 JdbcTemplate一起工作。

Spring對(duì)數(shù)據(jù)庫(kù)的操作在jdbc上面做了深層次的封裝,使用spring的注入功能,可以把DataSource注冊(cè)到JdbcTemplate之中。 JdbcTemplate 是在JDBC API基礎(chǔ)上提供了更抽象的封裝,并提供了基于方法注解的事務(wù)管理能力。 通過使用SpringBoot自動(dòng)配置功能并代替我們自動(dòng)配置beans.

數(shù)據(jù)源配置

在maven中,我們需要增加spring-boot-starter-jdbc模塊

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

通過這個(gè)模塊為我們做了以下幾件事

    tomcat-jdbc-{version}.jar為我們自動(dòng)配置DataSource.

    如果你沒有定義任何DataSource,SpringBoot將會(huì)自動(dòng)配置一個(gè)內(nèi)存的數(shù)據(jù)庫(kù)資源設(shè)置
    如果沒有設(shè)置任一個(gè)beans,SpringBoot會(huì)自動(dòng)注冊(cè)它
    初始化數(shù)據(jù)庫(kù)
    如果我們?cè)赾lasspath里定義了schema.sql和data.sql文件,springBoot將會(huì)使用這些文件自動(dòng)初始化數(shù)據(jù)庫(kù)(但你必須選建庫(kù))
    除了載入schema.sql和data.sql外,SpringBoot也會(huì)載入schema-${platform}.sql和data-${platform}.sql,如果在你的classpath下存在的話。

  spring.datasource.schema=xxxx-db.sql 可以定義你的建庫(kù)文件
  spring.datasource.data=xxxx-data.sql 可以定義你的數(shù)據(jù)文件
  spring.datasource.initialize=true|false 可以決定是不是要初始化這些數(shù)據(jù)庫(kù)文件
  spring.datasource.continueOnError=true|false 有了錯(cuò)誤是否繼續(xù)運(yùn)行

嵌入式數(shù)據(jù)庫(kù)支持

嵌入式數(shù)據(jù)庫(kù)通常用于開發(fā)和測(cè)試環(huán)境,不推薦用于生產(chǎn)環(huán)境。Spring Boot提供自動(dòng)配置的嵌入式數(shù)據(jù)庫(kù)有H2、HSQL、Derby,你不需要提供任何連接配置就能使用。

比如,我們可以在pom.xml中引入如下配置使用HSQL

<dependency>
 <groupId>org.hsqldb</groupId>
 <artifactId>hsqldb</artifactId>
 <scope>runtime</scope>
</dependency>

連接生產(chǎn)數(shù)據(jù)源配置

以MySQL數(shù)據(jù)庫(kù)為例,先引入MySQL連接的依賴包,在pom.xml中加入:

<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.21</version>
</dependency>

在src/main/resources/application.properties中配置數(shù)據(jù)源信息

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數(shù)據(jù)源配置

當(dāng)你將應(yīng)用部署于應(yīng)用服務(wù)器上的時(shí)候想讓數(shù)據(jù)源由應(yīng)用服務(wù)器管理,那么可以使用如下配置方式引入JNDI數(shù)據(jù)源。

spring.datasource.jndi-name=java:jboss/datasources/customers

自定義數(shù)據(jù)源配置

如果你不想用默認(rèn)的配置數(shù)據(jù)源,如你想用阿里巴巴的數(shù)據(jù)池管理數(shù)據(jù)源,你也可以自己配置

先排除tomcat-jdbc的默認(rèn)配置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>

定義自己的數(shù)據(jù)資源 這里使用了阿里巴巴的數(shù)據(jù)池管理,你也可以使用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;
}

代碼示例

創(chuàng)建實(shí)體對(duì)象

/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 + '\'' +
    '}';
 }
}

創(chuàng)建持久層

有了上面的數(shù)據(jù)源配置,我們可以注入JdbcTemplate到數(shù)據(jù)訪問組件并與數(shù)據(jù)庫(kù)交互。

/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;
 }
}

單元測(cè)試

你或許己注意到,大多數(shù)時(shí)候,我們都在應(yīng)用中做這些配置的事。

創(chuàng)建單元測(cè)試測(cè)試我們的持久層方法

/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());
 }
}

以上所述是小編給大家介紹的spring boot中使用JdbcTemplate,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

  • 使用Spring Security OAuth2實(shí)現(xiàn)單點(diǎn)登錄

    使用Spring Security OAuth2實(shí)現(xiàn)單點(diǎn)登錄

    在本教程中,我們將討論如何使用Spring Security OAuth和Spring Boot實(shí)現(xiàn)SSO - 單點(diǎn)登錄。感興趣的朋友跟隨小編一起看看吧
    2019-06-06
  • Spring?@Transactional事務(wù)失效的原因分析

    Spring?@Transactional事務(wù)失效的原因分析

    一個(gè)程序中不可能沒有事務(wù),Spring中,事務(wù)的實(shí)現(xiàn)方式分為兩種:編程式事務(wù)和聲明式事務(wù)。日常項(xiàng)目中,我們都會(huì)使用聲明式事務(wù)?@Transactional來實(shí)現(xiàn)事務(wù),本文來和大家聊聊什么情況會(huì)導(dǎo)致@Transactional事務(wù)失效
    2022-09-09
  • springmvc中進(jìn)行數(shù)據(jù)保存以及日期參數(shù)的保存過程解析

    springmvc中進(jìn)行數(shù)據(jù)保存以及日期參數(shù)的保存過程解析

    這篇文章主要介紹了springmvc中進(jìn)行數(shù)據(jù)保存以及日期參數(shù)的保存過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • 關(guān)于@Component注解下的類無法@Autowired問題

    關(guān)于@Component注解下的類無法@Autowired問題

    這篇文章主要介紹了關(guān)于@Component注解下的類無法@Autowired問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java設(shè)計(jì)模式之工廠方法和抽象工廠

    Java設(shè)計(jì)模式之工廠方法和抽象工廠

    本文詳細(xì)講解了Java設(shè)計(jì)模式之工廠方法和抽象工廠,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-09-09
  • Java線程池的工作機(jī)制詳解

    Java線程池的工作機(jī)制詳解

    本文講述了Java線程池的工作機(jī)制,包括線程池的創(chuàng)建、任務(wù)調(diào)度、線程復(fù)用、資源管理和拒絕策略,通過合理配置線程池參數(shù),可以提升系統(tǒng)的并發(fā)性能和穩(wěn)定性
    2024-12-12
  • Java 存儲(chǔ)模型和共享對(duì)象詳解

    Java 存儲(chǔ)模型和共享對(duì)象詳解

    這篇文章主要介紹了Java 存儲(chǔ)模型和共享對(duì)象詳解的相關(guān)資料,對(duì)Java存儲(chǔ)模型,可見性和安全發(fā)布的問題是起源于Java的存儲(chǔ)結(jié)構(gòu)及共享對(duì)象安全,需要的朋友可以參考下
    2017-03-03
  • Maven插件docker-maven-plugin的使用

    Maven插件docker-maven-plugin的使用

    在我們持續(xù)集成過程中,項(xiàng)目工程一般使用 Maven 編譯打包,然后生成鏡像,docker-maven-plugin 插件就是為了幫助我們?cè)贛aven工程中,通過簡(jiǎn)單的配置,自動(dòng)生成鏡像并推送到倉(cāng)庫(kù)中。感興趣的可以了解一下
    2021-06-06
  • Java正則驗(yàn)證字串符RegexValidator類使用

    Java正則驗(yàn)證字串符RegexValidator類使用

    正則驗(yàn)證字串符是一種強(qiáng)大的工具,可以幫助程序員在處理字符串時(shí)輕松進(jìn)行復(fù)雜匹配,本文將介紹正則表達(dá)式的概念、語法和在編程中的應(yīng)用,并通過實(shí)例演示如何使用正則表達(dá)式進(jìn)行字符串匹配、替換和提取等操作
    2023-11-11
  • 詳細(xì)聊聊SpringBoot中動(dòng)態(tài)切換數(shù)據(jù)源的方法

    詳細(xì)聊聊SpringBoot中動(dòng)態(tài)切換數(shù)據(jù)源的方法

    在大型分布式項(xiàng)目中,經(jīng)常會(huì)出現(xiàn)多數(shù)據(jù)源的情況,下面這篇文章主要給大家介紹了關(guān)于SpringBoot中動(dòng)態(tài)切換數(shù)據(jù)源的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2021-09-09

最新評(píng)論

会同县| 五指山市| 烟台市| 阳泉市| 嵩明县| 周口市| 广汉市| 外汇| 盈江县| 都昌县| 德昌县| 四平市| 昭觉县| 米林县| 南澳县| 田林县| 江油市| 察隅县| 崇明县| 沁水县| 古交市| 天水市| 尚义县| 筠连县| 昭苏县| 名山县| 临西县| 桐梓县| 昌邑市| 敖汉旗| 涪陵区| 安平县| 绥芬河市| 卓尼县| 新巴尔虎右旗| 巴林右旗| 镇沅| 固安县| 金阳县| 荆州市| 承德县|