spring-boot-JdbcTemplate

添加依赖

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

自定义数据源

spring-boot-starter-jdbc 默认使用tomcat-jdbc数据源

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.19</version>
</dependency>

数据源配置

spring.datasource.url = jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

配置自己的数据源

@Autowired
    private Environment env;

    //destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
    @Bean(destroyMethod = "close")
    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"));
        //初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
        dataSource.setInitialSize(2);
        //最大连接池数量
        dataSource.setMaxActive(20);
        //最小连接池数量
        dataSource.setMinIdle(0);
        //获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,
        //如果需要可以通过配置 useUnfairLock属性为true使用非公平锁。
        dataSource.setMaxWait(60000);
        //用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。
        //如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
        dataSource.setValidationQuery("SELECT 1");
        //申请连接时执行 validationQuery检测连接是否有效,做了这个配置会降低性能。
        dataSource.setTestOnBorrow(false);
        //建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,
        // 如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
        dataSource.setTestWhileIdle(true);
        //是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,
        // 比如说oracle。在mysql下建议关闭。
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }

定义实体对象

public class LearnResouce {
    private Long id;
    private String author;
    private String title;
    private String url;
	// SET和GET方法
}

定义dao接口

public interface LearnDao {
    int add(LearnResouce learnResouce);
    int update(LearnResouce learnResouce);
    int deleteByIds(String ids);
    LearnResouce queryLearnResouceById(Long id);
    Page queryLearnResouceList(Map<String,Object> params);
}

定义 dao 实现

@Repository
public class LearnDaoImpl implements LearnDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(LearnResouce learnResouce) {
        return jdbcTemplate.update("insert into learn_resource(author, title,url) values(?, ?, ?)",
                learnResouce.getAuthor(), learnResouce.getTitle(), learnResouce.getUrl());
    }

    @Override
    public int update(LearnResouce learnResouce) {
        return jdbcTemplate.update("update learn_resource set author=?,title=?,url=? where id = ?",
                new Object[]{learnResouce.getAuthor(), learnResouce.getTitle(), learnResouce.getUrl(),
                        learnResouce.getId()});
    }

    @Override
    public int deleteByIds(String ids) {
        return jdbcTemplate.update("delete from learn_resource where id in(" + ids + ")");
    }

    @Override
    public LearnResouce queryLearnResouceById(Long id) {
        List<LearnResouce> list = jdbcTemplate.query("select * from learn_resource where id = ?",
                new Object[]{id}, new BeanPropertyRowMapper(LearnResouce.class));
        if (null != list && list.size() > 0) {
            LearnResouce learnResouce = list.get(0);
            return learnResouce;
        } else {
            return null;
        }
    }

    @Override
    public Page queryLearnResouceList(Map<String, Object> params) {
        StringBuffer sql = new StringBuffer();
        sql.append("select * from learn_resource where 1=1");
        if (!StringUtil.isNull((String) params.get("author"))) {
            sql.append(" and author like '%").append((String) params.get("author")).append("%'");
        }
        if (!StringUtil.isNull((String) params.get("title"))) {
            sql.append(" and title like '%").append((String) params.get("title")).append("%'");
        }
        Page page = new Page(sql.toString(), Integer.parseInt(params.get("page").toString()),
                Integer.parseInt(params.get("rows").toString()), jdbcTemplate);
        return page;
    }
}

参考:

原始链接:http://tengj.top/2017/04/13/springboot8/

posted @ 2018-12-06 17:38  张建斌  阅读(458)  评论(0编辑  收藏  举报