org.springframework.boot
spring-boot-starter-data-jpa
mysql
mysql-connector-java
runtime
com.zaxxer
HikariCP
3.1.0
com.alibaba
fastjson
1.2.47
在application.properties中添加数据库配置,可在正式环境中加大maximum-pool-size值
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bigdata?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=15000&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
# Hikari will use the above plus the following to setup connection pooling
# type就是指定使用什么数据源,可以是Hikari、Druid等
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=25
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=ExpendHikariCP
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1
接下来需要在项目中添加entity、repository 架包
在entity架包下,添加 User.java文件,与数据库表字段对应,本文使用spring-data-jpa,后面会分享mybatis
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //id自动增长
private int id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private int age;
getter and setter ...
}
在repository架包下,新建UserRepository.java文件,继承 CrudRepository
@Repository
@Transactional
public interface UserRepository extends CrudRepository {
/**
* 由JPA自动根据方法名生成查询sql
* @param id
* @return
*/
User findById(int id);
User findByName(String name);
void deleteById(int id);
//自定义sql
@Modifying
@Query(value = "select * from user",nativeQuery = true)
List findAll();
}
再创建service架包,在其下添加inf、impl架包,分别在其下添加接口与实现
public interface IUserService {
void add(User user);
void edit(User user);
void delete(int id);
User findById(int id);
User findByName(String name);
List findAll();
}
@Service
public class UserServiceImpl implements IUserService{
@Autowired private UserRepository userRepository;
@Override
public void add(User user) {
userRepository.save(user);
}
@Override
public void edit(User user) {
userRepository.save(user);
}
@Override
public void delete(int id) {
userRepository.deleteById(id);
}
@Override
public User findById(int id) {
return userRepository.findById(id);
}
@Override
public User findByName(String name) {
return userRepository.findByName(name);
}
@Override
public List findAll() {
return userRepository.findAll();
}
}
最后,对写的代码进行测试,新建一个测试类,内容如下,右键测试方法点击运行一一测试,下面有测试图片,其中项目结构也在图片中,把user对象打印成字符串,就需要用到fastjson进行序列化
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {
@Autowired private IUserService userService;
@Test
public void add(){
User user = new User();
user.setName("zy");
user.setAge(26);
userService.add(user);
}
@Test
public void edit(){
User user = new User();
user.setId(1);
user.setName("zy1");
user.setAge(22);
userService.edit(user);
}
@Test
public void delete(){
userService.delete(1);
}
@Test
public void findById(){
User user = userService.findById(1);
System.out.println("user content :" + JSON.toJSONString(user));
}
@Test
public void findByName(){
User user = userService.findByName("zy1");
System.out.println("user content :" + JSON.toJSONString(user));
}
@Test
public void findAll(){
List list = userService.findAll();
System.out.println("user content :" + JSON.toJSONString(list));
}
}
执行add方法后
再来一个findById方法,其他的大家自行测试
下一篇集成:Mybatis框架
如果想使用阿里的Druid,可以添加依赖,在配置文件中加入自定义配置(线程池大小等)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
spring:
datasource:
# 数据源基本配置
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/duid
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
然后添加一个配置类,使用这些自定义配置,配置监控后台Servlet,配置filter
@Configuration
public class DruidConfig{
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DruidDataSource druidDataSource(){
return new DruidDataSource();
}
//配置监控servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet() , "/druid/*");
Map<String,String> initParameter= new HashMap<>();
initParameter.put("loginUsername" ,"admin");
initParameter.put("loginPassword" ,"123456");
initParameter.put("allow" ,"");//默认允许所有访问
// 添加IP白名单
//servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高
//servletRegistrationBean.addInitParameter("deny", "127.0.0.1");
// 是否能够重置数据
servletRegistrationBean.addInitParameter("resetEnable", "false");
bean.setInitParameters(initParameter);
return bean;
}
//配置监控filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
// 添加过滤规则
bean .addUrlPatterns("/*");
// 忽略过滤格式
bean .addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*,");
return bean;
}
}
配置完后我们启动SpringBoot程序访问:
http://localhost:8080/druid/ 就可以来到我们的登录页面面就是我们上面添加的控制台管理用户,我们可以在上面很好的看到运行状况和Sql执行情况