一:POM依赖
<dependency> <groupId>org.nutz</groupId> <artifactId>nutz</artifactId> <version>1.r.56</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.16</version> </dependency>
二:yml 文件
spring:
datasource:
url: jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true username: root password: gozapdev driver-class-name: com.mysql.jdbc.Driver initial-size: 3 max-active: 20 min-idle: 2 validation-query: SELECT 1
三: DbConfiguration
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DBConfiguration {
public static ConcurrentHashMap<String, Dao> concurrentHashMap;
private String url;
private String username;
private String password;
private String driverClassName;
private Integer initialSize;
private Integer maxActive;
private Integer minIdle;
private String validationQuery;
@PostConstruct
public void init(){
Dao dao = getSysBaseDao();
concurrentHashMap = new ConcurrentHashMap();
concurrentHashMap.put("dbname",dao);
}
public Dao getSysBaseDao() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(minIdle);
dataSource.setPoolPreparedStatements(true);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setPoolPreparedStatements(true);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(true);
Dao dao = new NutDao(dataSource);
return dao;
}
}
四:使用
1:
public static Timestamp getMaxActionStamp(Long groupID) throws Exception{
Dao dao = DBSysBaseConfiguration.concurrentHashMap.get("dbname");
String sqlStr = "SELECT max(actionStamp) as actionStamp FROM 表 WHERE groupID = @groupID AND action IN (0,1)";
Sql sql = Sqls.create(sqlStr);
sql.setParam("groupID", groupID);
sql.setCallback(new SqlCallback(){
@Override
public Object invoke(Connection connection, ResultSet rs, Sql sql) throws SQLException {
Timestamp result = null;
while (rs.next()){
result = rs.getTimestamp("actionStamp");
}
return result;
}
});
dao.execute(sql);
return sql.getObject(Timestamp.class);
}
2:
public static List<AAA> getAAAList(Long groupID) throws Exception{
Dao dao = DBSysBaseConfiguration.concurrentHashMap.get("dbname");
String sqlStr = "SELECT aa from biao where groupID = @groupID ";
StringBuilder sqlApp = new StringBuilder(sqlStr);
Sql sql = Sqls.create(sqlApp.toString());
sql.setParam("groupID", groupID);
sql.setCallback(new SqlCallback(){
@Override
public List<AAA> invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
List<AAA> list = new ArrayList<>();
while (rs.next()){
AAA model = new AAA();
model.setCreateBy(createByContent);
list.add(model);
}
return list;
}
});
dao.execute(sql);
return sql.getList(AAA.class);
}