SpringBoot:使用JdbcTemplate

Spring使用JdbcTemplate在JDBC API的基础上提供了一个很好的抽象,并且还使用基于注释的方法提供了强大的事务管理功能。

首先,通过注册DataSourceTransactionManagerJdbcTemplate Bean,快速看一下我们通常如何使用Spring的JdbcTemplate不带 SpringBoot ),并且可以选择注册DataSourceInitializer Bean来初始化数据库。

@Configuration
@ComponentScan
@EnableTransactionManagement
@PropertySource(value = { "classpath:application.properties" })
public class AppConfig 
{
    @Autowired
    private Environment env;

    @Value("${init-db:false}")
    private String initDatabase;
    
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }    

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource)
    {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource)
    {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public 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;
    }

    @Bean
    public 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
{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(readOnly=true)
    public List<User> findAll() {
        return jdbcTemplate.query("select * from users", new UserRowMapper());
    }
}
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;
    }
}

您可能已经观察到,大多数时候我们在应用程序中使用这种类似的配置。

现在让我们看看如何使用JdbcTemplate而不需要通过使用SpringBoot手动配置所有这些bean。

通过使用SpringBoot,我们可以利用自动配置功能,而无需自己配置bean。

创建一个基于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,并且在类路径中有任何嵌入式数据库驱动程序(例如H2,HSQL或Derby),那么SpringBoot将使用内存中的数据库设置自动注册DataSource bean。
  • 如果您还没有注册任何以下类型的bean,那么SpringBoot将自动注册它们。
    • PlatformTransactionManager(DataSourceTransactionManager)
  • 我们可以有schema.sql文件和根类路径data.sql文件,这SpringBoot会自动使用初始化database.In除了schema.sql文件和data.sql,春天开机就会加载的架构- $ {}平台的.sql数据$ {platform} .sql文件(如果在根类路径中可用)。 这里的平台值是属性spring.datasource.platform的值,可以是hsqldb,h2,oracle,mysql,postgresql等 。您可以使用以下属性来自定义脚本的默认名称:
    • spring.datasource.schema =创建db.sql

让我们将H2数据库驱动程序添加到我们的pom.xml中

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</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','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');

现在,可以将JdbcTemplate注入到UserRepository中 ,如下所示:

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

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

创建入口点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
{
    @Autowired
    private UserRepository userRepository;

    @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);
    }

    @Test
    public 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());
    }
}

默认情况下,仅当您使用SpringApplication时 ,ApplicationContext中才能使用诸如外部属性,日志记录之类的SpringBoot功能。 因此,SpringBoot提供@SpringApplicationConfiguration批注以配置ApplicationContext进行测试,该测试在后台使用SpringApplication

我们已经学习了如何快速开始使用嵌入式数据库。 如果我们想使用MySQL,Oracle或PostgreSQL等非嵌入式数据库怎么办?

我们可以在application.properties文件中配置数据库属性,以便SpringBoot将使用那些jdbc参数来配置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会导入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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值