参考博客 http://tengj.top/2017/04/13/springboot8/
项目地址:https://github.com/snjl/springboot.jdbcTemplete.git
添加依赖
1 | 在pom.xml里添加spring-boot-starter-jdbc依赖跟mysql依赖: |
数据源配置
在src/main/resources/application.properties中配置数据源信息:1
2
3
4spring.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
自定义数据源
添加mysql依赖(spring-boot-starter-jdbc 默认使用tomcat-jdbc数据源,如果要使用其他数据源,需要添加额外的依赖,这里使用了阿里巴巴的数据池管理):1
2
3
4
5<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
修改Application.java:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40package com.dudu;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import javax.sql.DataSource;
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
private Environment env;
//destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
"close") (destroyMethod =
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);//初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
dataSource.setMaxActive(20);//最大连接池数量
dataSource.setMinIdle(0);//最小连接池数量
dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
return dataSource;
}
}
Spring Boot会智能地选择我们自己配置的这个DataSource实例。
脚本初始化
1 |
|
使用JdbcTemplate
Spring的JdbcTemplate是自动配置的,可以直接使用@Autowired来注入到自己的bean中来使用。这里做了一套增伤改查。
pojo类:1
2
3
4
5
6
7public class LearnResouce {
private Long id;
private String author;
private String title;
private String url;
// SET和GET方法
}
dao层的接口实现:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62package com.dudu.dao.impl;
import com.dudu.dao.LearnDao;
import com.dudu.domain.LearnResouce;
import com.dudu.tools.Page;
import com.dudu.tools.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
/**
* Created by tengj on 2017/4/8.
*/
public class LearnDaoImpl implements LearnDao{
private JdbcTemplate jdbcTemplate;
public int add(LearnResouce learnResouce) {
return jdbcTemplate.update("insert into learn_resource(author, title,url) values(?, ?, ?)",learnResouce.getAuthor(),learnResouce.getTitle(),learnResouce.getUrl());
}
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()});
}
public int deleteByIds(String ids){
return jdbcTemplate.update("delete from learn_resource where id in("+ids+")");
}
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;
}
}
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;
}
}
其中值得注意的几个点:
- jdbcTemplete直接使用@Autowired注解注入的;
- deleteByIds这个方法是传入的数据是形如”(1,2,3,5)”这样的数据,是在controller里或者前端组装好的;
- queryLearnResouceList这个方法返回的是一个Page对象,它需要的参数里有一个page,指的是当前页码,下面是Page.java的代码:
1 | package com.dudu.tools; |
Page的构造函数,将sql和其他条件拼接起来,从而得到每一页的信息。最后返回一个List<Map<String, Object>>对象和一些例如页码数、总数据条数等数据,作为一个Page数据。
Service层
没有特点。
Controller层
1 | package com.dudu.controller; |
这里使用了ServletUtil,在此仅举出一例:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 public static String createSuccessResponse(Integer httpCode, Object result, SerializerFeature serializerFeature, SerializeFilter filter, HttpServletResponse response){
PrintWriter printWriter = null;
String jsonString = "";
try {
response.setCharacterEncoding(RESPONSE_CHARACTERENCODING);
response.setContentType(RESPONSE_CONTENTTYPE);
response.setStatus(httpCode);
printWriter = response.getWriter();
if(null != result){
if(null!=filter){
jsonString = JSONObject.toJSONString(result,filter,serializerFeature);
}else{
// jsonString = JSONObject.toJSONString(result, serializerFeature);
jsonString = JSONObject.toJSONStringWithDateFormat(result,"yyyy-MM-dd HH:ss:mm",serializerFeature);
}
printWriter.write(jsonString);
}
printWriter.flush();
} catch (Exception e) {
log.error("createResponse failed", e);
} finally {
if(null!=printWriter)printWriter.close();
}
return jsonString;
}