1.5JdbcTmeplates、Jpa、Mybatis、beatlsql、Druid的使用

Spring boot 连接数据库整合

-- create table `account`
DROP TABLE `account` IF EXISTS
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');

在application.properties文件配置mysql的驱动类,数据库地址,数据库账号、密码信息。

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root

引入mysql连接类和连接池:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

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

JdbcTemplates访问Mysql

在pom文件引入spring-boot-starter-jdbc的依赖:

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



dao

public interface IAccountDAO {
int add(Account account);

int update(Account account);

int delete(int id);

Account findAccountById(int id);

List<Account> findAccountList();
}

class

@Repository
public class AccountDaoImpl implements IAccountDAO {

@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int add(Account account) {
return jdbcTemplate.update("insert into account(name, money) values(?, ?)",
account.getName(),account.getMoney());

}

@Override
public int update(Account account) {
return jdbcTemplate.update("UPDATE account SET NAME=? ,money=? WHERE id=?",
account.getName(),account.getMoney(),account.getId());
}

@Override
public int delete(int id) {
return jdbcTemplate.update("DELETE from TABLE account where id=?",id);
}

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

@Override
public List<Account> findAccountList() {
List<Account> list = jdbcTemplate.query("select * from account", new Object[]{}, new BeanPropertyRowMapper(Account.class));
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
}
}

SpringBoot 整合JPA

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa </artifactId> </dependency>

dao

public interface AccountDao extends JpaRepository<Account,Integer> { }

class

@RestController
@RequestMapping("/account")
public class AccountController {

@Autowired
AccountDao accountDao;

@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<Account> getAccounts() {
return accountDao.findAll();
}

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Account getAccountById(@PathVariable("id") int id) {
return accountDao.findOne(id);
}

@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
@RequestParam(value = "money", required = true) double money) {
Account account = new Account();
account.setMoney(money);
account.setName(name);
account.setId(id);
Account account1 = accountDao.saveAndFlush(account);

return account1.toString();

}

@RequestMapping(value = "", method = RequestMethod.POST)
public String postAccount(@RequestParam(value = "name") String name,
@RequestParam(value = "money") double money) {
Account account = new Account();
account.setMoney(money);
account.setName(name);
Account account1 = accountDao.save(account);
return account1.toString();

}


}

springboot整合mybatis

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter<artifactId>
<version>1.3.0</version>
</dependency>

dao

@Mapper
public interface AccountMapper {

@Insert("insert into account(name, money) values(#{name}, #{money})")
int add(@Param("name") String name, @Param("money") double money);

@Update("update account set name = #{name}, money = #{money} where id = #{id}")
int update(@Param("name") String name, @Param("money") double money, @Param("id") int id);

@Delete("delete from account where id = #{id}")
int delete(int id);

@Select("select id, name as name, money as money from account where id = #{id}")
Account findAccount(@Param("id") int id);

@Select("select id, name as name, money as money from account")
List<Account> findAccountList();
}

springboot整合 beatlsql

<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>2.3.2</version>

</dependency>

<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetlsql</artifactId>
<version>2.3.1</version>

</dependency>

由于springboot没有对 beatlsql的快速启动装配,所以需要我自己导入相关的bean,包括数据源,包扫描,事物管理器等。

在application加入以下代码:


@Bean(initMethod = "init", name = "beetlConfig")
public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration();
ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
try {
// WebAppResourceLoader 配置root路径是关键
WebAppResourceLoader webAppResourceLoader = new WebAppResourceLoader(patternResolver.getResource("classpath:/templates").getFile().getPath());
beetlGroupUtilConfiguration.setResourceLoader(webAppResourceLoader);
} catch (IOException e) {
e.printStackTrace();
}
//读取配置文件信息
return beetlGroupUtilConfiguration;

}

@Bean(name = "beetlViewResolver")
public BeetlSpringViewResolver getBeetlSpringViewResolver(@Qualifier("beetlConfig") BeetlGroupUtilConfiguration beetlGroupUtilConfiguration) {
BeetlSpringViewResolver beetlSpringViewResolver = new BeetlSpringViewResolver();
beetlSpringViewResolver.setContentType("text/html;charset=UTF-8");
beetlSpringViewResolver.setOrder(0);
beetlSpringViewResolver.setConfig(beetlGroupUtilConfiguration);
return beetlSpringViewResolver;
}

//配置包扫描
@Bean(name = "beetlSqlScannerConfigurer")
public BeetlSqlScannerConfigurer getBeetlSqlScannerConfigurer() {
BeetlSqlScannerConfigurer conf = new BeetlSqlScannerConfigurer();
conf.setBasePackage("com.forezp.dao");
conf.setDaoSuffix("Dao");
conf.setSqlManagerFactoryBeanName("sqlManagerFactoryBean");
return conf;
}

@Bean(name = "sqlManagerFactoryBean")
@Primary
public SqlManagerFactoryBean getSqlManagerFactoryBean(@Qualifier("datasource") DataSource datasource) {
SqlManagerFactoryBean factory = new SqlManagerFactoryBean();

BeetlSqlDataSource source = new BeetlSqlDataSource();
source.setMasterSource(datasource);
factory.setCs(source);
factory.setDbStyle(new MySqlStyle());
factory.setInterceptors(new Interceptor[]{new DebugInterceptor()});
factory.setNc(new UnderlinedNameConversion());//开启驼峰
factory.setSqlLoader(new ClasspathLoader("/sql"));//sql文件路径
return factory;
}


//配置数据库
@Bean(name = "datasource")
public DataSource getDataSource() {
return DataSourceBuilder.create().url("jdbc:mysql://127.0.0.1:3306/test").username("root").password("123456").build();
}

//开启事务
@Bean(name = "txManager")
public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("datasource") DataSource datasource) {
DataSourceTransactionManager dsm = new DataSourceTransactionManager();
dsm.setDataSource(datasource);
return dsm;
}

在resouces包下,加META_INF文件夹,文件夹中加入spring-devtools.properties:

restart.include.beetl=/beetl-2.3.2.jar
restart.include.beetlsql=/beetlsql-2.3.1.jar

加入jar和配置beatlsql的这些bean,以及resources这些配置之后,springboot就能够访问到数据库类。

数据访问dao层
public interface AccountDao extends BaseMapper<Account> {

@SqlStatement(params = "name")
Account selectAccountByName(String name);
}

Spring Boot集成Druid实现数据源管理与监控

Druid是阿里开源的一个JDBC应用组件, 其包括三部分:

DruidDriver 代理Driver,能够提供基于Filter-Chain模式的插件体系。
DruidDataSource 高效可管理的数据库连接池。
SQLParser SQL语法分析
通过Druid连接池中间件, 我们可以实现:

可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
替换传统的DBCP和C3P0连接池中间件。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件。

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>

Spring Boot配置文件配置

Spring Boot配置文件有application.properties和application.yml两种配置文件方式 , 此处采用的是application.yml的配置方式。

# Spring Datasource Settings
spring:
datasource:
name: druidDataSource
type: com.alibaba.druid.pool.DruidDataSource
druid:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.202.17:3306/auth_service?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false
username: root
password: 123456
filters: stat,wall,log4j,config
max-active: 100
initial-size: 1
max-wait: 60000
min-idle: 1
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: select 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-open-prepared-statements: 50
max-pool-prepared-statement-per-connection-size: 20

说明:
- spring.datasource.druid.max-active 最大连接数
- spring.datasource.druid.initial-size 初始化大小
- spring.datasource.druid.min-idle 最小连接数
- spring.datasource.druid.max-wait 获取连接等待超时时间
- spring.datasource.druid.time-between-eviction-runs-millis 间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
- spring.datasource.druid.min-evictable-idle-time-millis 一个连接在池中最小生存的时间,单位是毫秒
- spring.datasource.druid.filters=config,stat,wall,log4j 配置监控统计拦截的filters,去掉后监控界面SQL无法进行统计,’wall’用于防火墙

Druid提供以下几种Filter信息:

Filter类名 ===别名
default ===com.alibaba.druid.filter.stat.StatFilter
stat ===com.alibaba.druid.filter.stat.StatFilter
mergeStat ===com.alibaba.druid.filter.stat.MergeStatFilter
encoding ===com.alibaba.druid.filter.encoding.EncodingConvertFilter
log4j ===com.alibaba.druid.filter.logging.Log4jFilter
log4j2 ===com.alibaba.druid.filter.logging.Log4j2Filter
slf4j ===com.alibaba.druid.filter.logging.Slf4jLogFilter
commonlogging ===com.alibaba.druid.filter.logging.CommonsLogFilter
wall ===com.alibaba.druid.wall.WallFilter

猜你喜欢

转载自www.cnblogs.com/sovy/p/11547086.html