Use 1.5JdbcTmeplates, Jpa, Mybatis, beatlsql, Druid's

Spring boot connect to the database integration

-- 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');

Mysql configuration file in application.properties drive category, address database, database account and password information.

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

Introducing mysql connection and connection pool class:

<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 Access Mysql

Introducing spring-boot-starter-jdbc pom in dependence file:

<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 integration 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 integration 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 integration 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>

Since springboot no assembly beatlsql quick start, so I need to import the relevant bean, including data sources, including scanning, management and other things.

In the application adding the following code:


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

In resouces package, plus META_INF folder, the folder is added spring-devtools.properties:

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

Join jar and configuration beatlsql of these bean, as well as after the resources of these configurations, springboot can access to the database category.

Dao data access layer
public interface AccountDao extends BaseMapper <Account> {

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

Spring Boot Druid achieve integrated data source management and monitoring

Druid is a JDBC Ali open source application components, which consists of three parts:

DruidDriver agents Driver, provides plug-in architecture based on Filter-Chain mode.
DruidDataSource efficient database connection pool can be managed.
SQLParser SQL parser
connection pool middleware through Druid, we can achieve:

Can monitor database access performance, Druid built provides a powerful StatFilter plugin that detailed statistics on the performance of SQL execution, which is helpful for online access performance analysis database.
Alternatively traditional middleware DBCP and C3P0 connection pool. Druid provides an efficient, powerful, scalable database connection pool.
Database password encryption. Write directly to the database password in the configuration file, which is not good behavior, easily lead to security problems. DruidDruiver and DruidDataSource support PasswordCallback.
SQL execution log, Druid offers different LogFilter, to support Common-Logging, Log4j and JdkLog, you can press the need to select the appropriate LogFilter, database monitoring visits your application.
Extended JDBC, if you want to have a demand programming for JDBC layer, Filter-Chain mechanism may be provided by the Druid, it is easy to write extensions JDBC layer.

<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 Configuration Profiles

Spring Boot configuration file has application.properties and application.yml two configuration files ways, using here is application.yml configured.

# 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

Description:
- the maximum number of connections spring.datasource.druid.max-Active
- spring.datasource.druid.initial-size the initial size
- minimum number of connections IDLE-spring.datasource.druid.min
- the wait-spring.datasource.druid.max obtaining a connection wait timeout
- spring.datasource.druid.time-between-eviction-runs -millis interval frequency of such detection, an idle connection is detected to be closed, in milliseconds
- spring.datasource.druid.min-evictable-idle -time-millis a minimum connection time survival pool milliseconds
- spring.datasource.druid.filters = config, stat, wall , log4j configuration monitoring statistics Filters intercept, not SQL interface monitoring statistics after removal, ' wall 'firewalls

Druid Filter provides the following information:

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

 

Guess you like

Origin www.cnblogs.com/sovy/p/11547086.html