网页设计与网站建设主要内容,网络营销推广活动方案,贸易公司网站案例,行业信息网站建设方案Spring使用JdbcTemplate在JDBC API的基础上提供了一个很好的抽象#xff0c;并且还使用基于注释的方法提供了强大的事务管理功能。 首先#xff0c;通过注册DataSource #xff0c; TransactionManager和JdbcTemplate Bean#xff0c;快速浏览一下我们通常如何使用Spring的… Spring使用JdbcTemplate在JDBC API的基础上提供了一个很好的抽象并且还使用基于注释的方法提供了强大的事务管理功能。 首先通过注册DataSource TransactionManager和JdbcTemplate Bean快速浏览一下我们通常如何使用Spring的JdbcTemplate 不带 SpringBoot 并且可以选择注册DataSourceInitializer Bean来初始化数据库。 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组件中以与数据库进行交互。 public class User
{private Integer id;private String name;private String email;// setters getters
}Repository
public class UserRepository
{Autowiredprivate JdbcTemplate jdbcTemplate;Transactional(readOnlytrue)public ListUser findAll() {return jdbcTemplate.query(select * from users, new UserRowMapper());}
}class UserRowMapper implements RowMapperUser
{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;}
} 您可能已经观察到大多数时候我们在应用程序中使用这种类似的配置。 现在让我们看看如何使用JdbcTemplate而不需要通过使用SpringBoot手动配置所有这些bean。 在 通过使用SpringBoot我们可以利用自动配置功能而无需自己配置bean。 创建一个基于SpringBoot Maven的项目并添加spring-boot-starter-jdbc模块。 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-jdbc/artifactId
/dependency 通过添加spring-boot-starter-jdbc模块我们得到以下自动配置 spring-boot-starter-jdbc模块可传递地拉出用于配置DataSource bean的tomcat-jdbc- {version} .jar。 如果您没有明确定义任何DataSource bean并且在类路径中有任何嵌入式数据库驱动程序例如H2HSQL或Derby那么SpringBoot将使用内存中的数据库设置自动注册DataSource bean。 如果您还没有注册任何以下类型的bean那么SpringBoot将自动注册它们。 PlatformTransactionManagerDataSourceTransactionManager 我们可以有schema.sql文件和根类路径data.sql文件这SpringBoot会自动使用初始化database.In除了schema.sql文件和data.sql春天开机就会加载的架构- $ {}平台的.sql和数据$ {platform} .sql文件如果在根类路径中可用。 这里的平台值是spring.datasource.platform属性的值可以是hsqldbh2oraclemysqlpostgresql等 。您可以使用以下属性来自定义脚本的默认名称 spring.datasource.schema 创建db.sql 让我们将H2数据库驱动程序添加到我们的pom.xml中 。 dependencygroupIdcom.h2database/groupIdartifactIdh2/artifactId
/dependency 在src / main / resources中创建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中创建data.sql 如下所示 insert into users(id, name, email) values(1,Siva,sivagmail.com);
insert into users(id, name, email) values(2,Prasad,prasadgmail.com);
insert into users(id, name, email) values(3,Reddy,reddygmail.com); 现在可以将JdbcTemplate注入到UserRepository中 如下所示 Repository
public class UserRepository
{Autowiredprivate JdbcTemplate jdbcTemplate;Transactional(readOnlytrue)public ListUser findAll() {return jdbcTemplate.query(select * from users, new UserRowMapper());}Transactional(readOnlytrue)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 RowMapperUser
{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;}
} 创建入口点SpringbootJdbcDemoApplication.java 。 SpringBootApplication
public class SpringbootJdbcDemoApplication
{public static void main(String[] args){SpringApplication.run(SpringbootJdbcDemoApplication.class, args);}
} 让我们创建一个JUnit Test类来测试我们的UserRepository方法。 RunWith(SpringJUnit4ClassRunner.class)
SpringApplicationConfiguration(SpringbootJdbcDemoApplication.class)
public class SpringbootJdbcDemoApplicationTests
{Autowiredprivate UserRepository userRepository;Testpublic void findAllUsers() {ListUser 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, johngmail.com);User savedUser userRepository.create(user);User newUser userRepository.findUserById(savedUser.getId());assertNotNull(newUser);assertEquals(John, newUser.getName());assertEquals(johngmail.com, newUser.getEmail());}
} 默认情况下仅当您使用SpringApplication时 ApplicationContext中才能使用诸如外部属性日志记录之类的SpringBoot功能。 因此SpringBoot提供SpringApplicationConfiguration批注以配置ApplicationContext进行测试该测试在后台使用SpringApplication 。 我们已经学习了如何快速开始使用嵌入式数据库。 如果我们想使用MySQLOracle或PostgreSQL等非嵌入式数据库怎么办 。 我们可以在application.properties文件中配置数据库属性以便SpringBoot将使用那些jdbc参数来配置DataSource bean。 spring.datasource.driver-class-namecom.mysql.jdbc.Driver
spring.datasource.urljdbc:mysql://localhost:3306/test
spring.datasource.usernameroot
spring.datasource.passwordadmin 出于任何原因如果您想自己控制和配置DataSource bean则可以在Configuration类中配置DataSource bean。 如果您注册DataSource bean那么SpringBoot将不会使用自动配置自动配置DataSource。 如果要使用另一个连接池库怎么办 默认情况下SpringBoot会导入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依赖项如下所示 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-jdbc/artifactIdexclusionsexclusiongroupIdorg.apache.tomcat/groupIdartifactIdtomcat-jdbc/artifactId/exclusion/exclusions
/dependencydependencygroupIdcom.zaxxer/groupIdartifactIdHikariCP/artifactId
/dependency 通过这种依赖性配置SpringBoot将使用HikariCP来配置DataSource bean。 翻译自: https://www.javacodegeeks.com/2016/03/springboot-working-jdbctemplate.html