SpringBoot+JDBC
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
从一张或多张表 查询出 某些需要的字段,并把它转为实体类。
比如有两张表table_a 和 table_b ,它们字段很多,某个功能只需要从这两张表中 获取某几个字段。
这样就可以新建一个实体类newEntity,它的字段就是需要获取到的字段。
然后用jdbc执行查询,并把结果转换成这个实体类。
新建实体类
public class NewEntity { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
执行查询,并把查询结果转为实体类List
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; @Service public class NewEntityServiceImplTest { @Autowired private JdbcTemplate jdbcTemplate; public List<NewEntity> findNewEntity(String strsqlColumn, String msac, String sbac) { String sqlString = "select ''as name,'' as age" + " from TB_ENTITY where class = '1' "; List<NewEntity> newEntities = jdbcTemplate.query(sqlString, new Object[] {}, new BeanPropertyRowMapper<NewEntity>(NewEntity.class)); return newEntities; } //如果结果只有一条 public NewEntity findNewEntity(String strsqlColumn, String msac, String sbac) { String sqlString = "select ''as name,'' as age" + " from TB_ENTITY where class = '1' "; NewEntity newEntity = jdbcTemplate.queryForObject(sqlString, NewEntity.class); return newEntity; } }