日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot:使用JdbcTemplate

發(fā)布時間:2023/12/3 javascript 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot:使用JdbcTemplate 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Spring使用JdbcTemplate在JDBC API的基礎(chǔ)上提供了一個很好的抽象,并且還使用基于注釋的方法提供了強大的事務(wù)管理功能。

首先,通過注冊DataSource , TransactionManager和JdbcTemplate Bean,快速瀏覽一下我們通常如何使用Spring的JdbcTemplate ( 不帶 SpringBoot ),并且可以選擇注冊DataSourceInitializer Bean來初始化數(shù)據(jù)庫。

@Configuration @ComponentScan @EnableTransactionManagement @PropertySource(value = { "classpath:application.properties" }) public class AppConfig {@Autowiredprivate Environment env;@Value("${init-db:false}")private String initDatabase;@Beanpublic static PropertySourcesPlaceholderConfigurer placeHolderConfigurer(){return new PropertySourcesPlaceholderConfigurer();} @Beanpublic JdbcTemplate jdbcTemplate(DataSource dataSource){return new JdbcTemplate(dataSource);}@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){return new DataSourceTransactionManager(dataSource);}@Beanpublic DataSource dataSource(){BasicDataSource dataSource = new BasicDataSource();dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));dataSource.setUrl(env.getProperty("jdbc.url"));dataSource.setUsername(env.getProperty("jdbc.username"));dataSource.setPassword(env.getProperty("jdbc.password"));return dataSource;}@Beanpublic DataSourceInitializer dataSourceInitializer(DataSource dataSource){DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); dataSourceInitializer.setDataSource(dataSource);ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();databasePopulator.addScript(new ClassPathResource("data.sql"));dataSourceInitializer.setDatabasePopulator(databasePopulator);dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase));return dataSourceInitializer;} }

使用此配置后,我們可以將JdbcTemplate注入到Data Access組件中以與數(shù)據(jù)庫進行交互。

public class User {private Integer id;private String name;private String email;// setters & getters }@Repository public class UserRepository {@Autowiredprivate JdbcTemplate jdbcTemplate;@Transactional(readOnly=true)public List<User> findAll() {return jdbcTemplate.query("select * from users", new UserRowMapper());} }class UserRowMapper implements RowMapper<User> {@Overridepublic 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;} }

您可能已經(jīng)觀察到,大多數(shù)時候我們在應(yīng)用程序中使用這種類似的配置。

現(xiàn)在讓我們看看如何使用JdbcTemplate而不需要通過使用SpringBoot手動配置所有這些bean。

通過使用SpringBoot,我們可以利用自動配置功能,而無需自己配置bean。

創(chuàng)建一個基于SpringBoot Maven的項目,并添加spring-boot-starter-jdbc模塊。

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

通過添加spring-boot-starter-jdbc模塊,我們得到以下自動配置:

  • spring-boot-starter-jdbc模塊可傳遞地拉出用于配置DataSource bean的tomcat-jdbc- {version} .jar。
  • 如果您沒有明確定義任何DataSource bean,并且在類路徑中有任何嵌入式數(shù)據(jù)庫驅(qū)動程序(例如H2,HSQL或Derby),那么SpringBoot將使用內(nèi)存中的數(shù)據(jù)庫設(shè)置自動注冊DataSource bean。
  • 如果您還沒有注冊任何以下類型的bean,那么SpringBoot將自動注冊它們。
    • PlatformTransactionManager(DataSourceTransactionManager)
  • 我們可以有schema.sql文件和根類路徑data.sql文件,這SpringBoot會自動使用初始化database.In除了schema.sql文件和data.sql,春天開機就會加載的架構(gòu)- $ {}平臺的.sql和數(shù)據(jù)$ {platform} .sql文件(如果在根類路徑中可用)。 這里的平臺值是spring.datasource.platform屬性的值,可以是hsqldb,h2,oracle,mysql,postgresql等 。您可以使用以下屬性來自定義腳本的默認名稱:
    • spring.datasource.schema =創(chuàng)建db.sql

讓我們將H2數(shù)據(jù)庫驅(qū)動程序添加到我們的pom.xml中 。

<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId> </dependency>

在src / main / resources中創(chuàng)建schema.sql ,如下所示:

CREATE TABLE users (id int(11) NOT NULL AUTO_INCREMENT,name varchar(100) NOT NULL,email varchar(100) DEFAULT NULL,PRIMARY KEY (id) );

在src / main / resources中創(chuàng)建data.sql ,如下所示:

insert into users(id, name, email) values(1,'Siva','siva@gmail.com'); insert into users(id, name, email) values(2,'Prasad','prasad@gmail.com'); insert into users(id, name, email) values(3,'Reddy','reddy@gmail.com');

現(xiàn)在,可以將JdbcTemplate注入到UserRepository中 ,如下所示:

@Repository public class UserRepository {@Autowiredprivate 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() {@Overridepublic 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;} }class UserRowMapper implements RowMapper<User> {@Overridepublic 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;} }

創(chuàng)建入口點SpringbootJdbcDemoApplication.java 。

@SpringBootApplication public class SpringbootJdbcDemoApplication {public static void main(String[] args){SpringApplication.run(SpringbootJdbcDemoApplication.class, args);} }

讓我們創(chuàng)建一個JUnit Test類來測試我們的UserRepository方法。

@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SpringbootJdbcDemoApplication.class) public class SpringbootJdbcDemoApplicationTests {@Autowiredprivate UserRepository userRepository;@Testpublic void findAllUsers() {List<User> users = userRepository.findAll();assertNotNull(users);assertTrue(!users.isEmpty());}@Testpublic void findUserById() {User user = userRepository.findUserById(1);assertNotNull(user);}@Testpublic void createUser() {User user = new User(0, "John", "john@gmail.com");User savedUser = userRepository.create(user);User newUser = userRepository.findUserById(savedUser.getId());assertNotNull(newUser);assertEquals("John", newUser.getName());assertEquals("john@gmail.com", newUser.getEmail());} }

默認情況下,僅當(dāng)您使用SpringApplication時 ,ApplicationContext中才能使用諸如外部屬性,日志記錄之類的SpringBoot功能。 因此,SpringBoot提供@SpringApplicationConfiguration批注以配置ApplicationContext進行測試,該測試在后臺使用SpringApplication 。

我們已經(jīng)學(xué)習(xí)了如何快速開始使用嵌入式數(shù)據(jù)庫。 如果我們想使用MySQL,Oracle或PostgreSQL等非嵌入式數(shù)據(jù)庫怎么辦? 。

我們可以在application.properties文件中配置數(shù)據(jù)庫屬性,以便SpringBoot將使用那些jdbc參數(shù)來配置DataSource bean。

spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=admin

出于任何原因,如果您想自己控制和配置DataSource bean,則可以在Configuration類中配置DataSource bean。 如果您注冊DataSource bean,那么SpringBoot將不會使用自動配置自動配置DataSource。 如果要使用另一個連接池庫怎么辦?

默認情況下,SpringBoot會導(dǎo)入tomcat-jdbc- {version} .jar并使用org.apache.tomcat.jdbc.pool.DataSource來配置DataSource bean。

SpringBoot檢查以下類的可用性,并使用在classpath中可用的第一個類。

  • org.apache.tomcat.jdbc.pool.DataSource
  • com.zaxxer.hikari.HikariDataSource
  • org.apache.commons.dbcp.BasicDataSource
  • org.apache.commons.dbcp2.BasicDataSource

例如,如果要使用HikariDataSource,則可以排除tomcat-jdbc并添加HikariCP依賴項,如下所示:

<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><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId> </dependency>

通過這種依賴性配置,SpringBoot將使用HikariCP來配置DataSource bean。

翻譯自: https://www.javacodegeeks.com/2016/03/springboot-working-jdbctemplate.html

總結(jié)

以上是生活随笔為你收集整理的SpringBoot:使用JdbcTemplate的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。