楔子
springJdbc封装实体类。自己做个笔记总结。方便日后查找,以免使用的时候在耽误时间到处找。
demo
使用的是springboot 2.0 默认的数据库连接池 为
com.zaxxer.hikari.HikariDataSource
import com.alibaba.fastjson.JSON;
import com.example.demo02.bean.DbType;
import com.example.demo02.bean.Dic;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.util.List;
//@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest
class Demo02ApplicationTests {
@Autowired
DataSourceProperties dataSourceProperties;
@Autowired
ApplicationContext applicationContext;
@Test
void contextLoads() {
DataSource dataSource = applicationContext.getBean(DataSource.class);
// 查看配置数据源信息
log.info("dataSource:{}", dataSource);
log.info("dataSource Name:{}", dataSource.getClass().getName());
System.out.println(dataSourceProperties);
//执行SQL,输出查到的数据
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<?> resultList = jdbcTemplate.queryForList("SELECT ID FROM ym_dic WHERE id=1");
System.out.println("===>>>>>>>>>>>" + JSON.toJSONString(resultList));
String sql = "SELECT t.`COLUMN_NAME` AS NAME ,t.`COLUMN_COMMENT` AS COMMENT FROM INFORMATION_SCHEMA.Columns t WHERE table_name='ym_fam'";
List<DbType> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DbType.class));
for (DbType dbType : query) {
System.out.println(dbType);
}
//查询封装实体类
List<Dic> query1 = jdbcTemplate.query("SELECT * FROM ym_dic where id =?", new String[]{"1"}, new BeanPropertyRowMapper(Dic.class));
System.out.println(query1);
}
}
打印结果
2019-10-21 20:33:08.140 INFO 15964 --- [ main] c.example.demo02.Demo02ApplicationTests : dataSource:HikariDataSource (HikariPool-1)
2019-10-21 20:33:08.140 INFO 15964 --- [ main] c.example.demo02.Demo02ApplicationTests : dataSource Name:com.zaxxer.hikari.HikariDataSource
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties@5cf2f5d6
===>>>>>>>>>>>[{"ID":1}]
com.example.demo02.bean.DbType@37ab1b10[name=id,comment=id]
com.example.demo02.bean.DbType@5b643d6e[name=name,comment=名称]
com.example.demo02.bean.DbType@34f8ce89[name=birthN,comment=农历]
com.example.demo02.bean.DbType@22ed2886[name=birthG,comment=阳历]
com.example.demo02.bean.DbType@30ca66c5[name=wish,comment=祝福语]
com.example.demo02.bean.DbType@4abfa2ff[name=CreateTime,comment=创建时间]
com.example.demo02.bean.DbType@38c1b1a7[name=addid,comment=添加人(主要是为了让人加入更多他人生日)]
com.example.demo02.bean.DbType@73230721[name=picpath,comment=图片路径]
com.example.demo02.bean.DbType@10bcbbce[name=isshow,comment=1显示 0不显示]
[Dic{id=1, diccode='sys_user_role', dicname='用户角色', dicitemcode='admin', dicitemname='管理员'}]