JdbcTemplate将查询出来的结果转换为对象


前言

JdbcTemplate是spring-jdbc包提供的模板类,本案例是在springboot配置完datasource基础上测试的。

一、准备

该方法仅适合数据库字段和java实体对象属性名完全对应的情况
数据库
在这里插入图片描述
StudentInfo.java

package com.student.model;

import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.lang.Character;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.lang.Integer;

/**
 * 学生基本信息 StudentInfo 
 * @date 2022-01-27 22:12:56
 */
 @ApiModel(value="StudentInfo", description="学生基本信息")
public class StudentInfo implements Serializable {

	private static final long serialVersionUID = 1L;
	
		
	/** 学号 **/
	@ApiModelProperty(value = "学号")
	private Integer id;
		
	/** 姓名 **/
	@ApiModelProperty(value = "姓名")
	private String name;
		
	/** 年龄 **/
	@ApiModelProperty(value = "年龄")
	private Integer age;
		
	/** 出生日期 **/
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
	@ApiModelProperty(value = "出生日期")
	private Date birthday;
		
	/** 民族 **/
	@ApiModelProperty(value = "民族")
	private String nation;
		
	/** 证件类型 **/
	@ApiModelProperty(value = "证件类型")
	private String idType;
		
	/** 证件号码 **/
	@ApiModelProperty(value = "证件号码")
	private String idNumber;
		
	/** 手机号 **/
	@ApiModelProperty(value = "手机号")
	private Integer tel;
		
	/** 入学时间 **/
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
	@ApiModelProperty(value = "入学时间")
	private Date admissionTime;
		
	/** 家庭住址 **/
	@ApiModelProperty(value = "家庭住址")
	private String address;
		
	/** 院系 **/
	@ApiModelProperty(value = "院系")
	private String faculty;
		
	/** 专业 **/
	@ApiModelProperty(value = "专业")
	private String major;
		
	/** 班级 **/
	@ApiModelProperty(value = "班级")
	private Integer classID;
		
	/** 辅导员 **/
	@ApiModelProperty(value = "辅导员")
	private String instructor;
		
	/** 是否在籍(0:否;1:是) **/
	@ApiModelProperty(value = "是否在籍(0:否;1:是)")
	private Character registered;
		
		
	public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
	 
			
	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;
    }
	 
			
	public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
	 
			
	public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }
	 
			
	public String getIdType() {
        return idType;
    }

    public void setIdType(String idType) {
        this.idType = idType;
    }
	 
			
	public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }
	 
			
	public Integer getTel() {
        return tel;
    }

    public void setTel(Integer tel) {
        this.tel = tel;
    }
	 
			
	public Date getAdmissionTime() {
        return admissionTime;
    }

    public void setAdmissionTime(Date admissionTime) {
        this.admissionTime = admissionTime;
    }
	 
			
	public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
	 
			
	public String getFaculty() {
        return faculty;
    }

    public void setFaculty(String faculty) {
        this.faculty = faculty;
    }
	 
			
	public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }
	 
			
	public Integer getClassID() {
        return classID;
    }

    public void setClassID(Integer classID) {
        this.classID = classID;
    }
	 
			
	public String getInstructor() {
        return instructor;
    }

    public void setInstructor(String instructor) {
        this.instructor = instructor;
    }
	 
			
	public Character getRegistered() {
        return registered;
    }

    public void setRegistered(Character registered) {
        this.registered = registered;
    }
	 
			
	public StudentInfo() {
        super();
    }
    
																																																																													
	public StudentInfo(Integer id,String name,Integer age,Date birthday,String nation,String idType,String idNumber,Integer tel,Date admissionTime,String address,String faculty,String major,Integer classID,String instructor,Character registered) {
	
		this.id = id;
		this.name = name;
		this.age = age;
		this.birthday = birthday;
		this.nation = nation;
		this.idType = idType;
		this.idNumber = idNumber;
		this.tel = tel;
		this.admissionTime = admissionTime;
		this.address = address;
		this.faculty = faculty;
		this.major = major;
		this.classID = classID;
		this.instructor = instructor;
		this.registered = registered;
		
	}

	@Override
	public String toString() {
		return "StudentInfo{" +
				"id=" + id +
				", name='" + name + '\'' +
				", age=" + age +
				", birthday=" + birthday +
				", nation='" + nation + '\'' +
				", idType='" + idType + '\'' +
				", idNumber='" + idNumber + '\'' +
				", tel=" + tel +
				", admissionTime=" + admissionTime +
				", address='" + address + '\'' +
				", faculty='" + faculty + '\'' +
				", major='" + major + '\'' +
				", classID=" + classID +
				", instructor='" + instructor + '\'' +
				", registered=" + registered +
				'}';
	}
}

二、测试案例

1.编写测试类

代码如下(示例):

package com.student;

import com.student.mapper.StudentInfoMapper;
import com.student.model.StudentInfo;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Create by zjg on 2022/9/25
 */
@RunWith(SpringRunner.class) //作用:让当前类在容器环境下进行测试
@SpringBootTest(classes = SpringbootStart.class)//作用:声明当前类是springboot的测试类并且获取入口类上的相关信息 SpringBootApplication是入口类类名
public class SpringbootStartTest {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    public void test(){
        jdbcQuery();
    }
    public void jdbcQuery(){
        String sql="select id,name,age,birthday from t_student_info limit 5";
        List<StudentInfo> studentInfoList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(StudentInfo.class));
        studentInfoList.forEach(System.out::println);
    }
    @Test
    public void jdbcQueryForList(){
        String sql="select id,name,age,birthday from t_student_info limit 5";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }
    }
}

jdbcQuery()
该处使用的url网络请求的数据。
jdbcQueryForList()
在这里插入图片描述


总结

有条件的情况下,还是要使用mybatis做映射,麻烦点但更符合规范。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例代码,演示如何使用JdbcTemplate查询返回一个List对象: ```java import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import java.util.List; public class MyDao { private JdbcTemplate jdbcTemplate; // 注入JdbcTemplate对象 // 查询所有用户 public List<User> findAllUsers() { String sql = "SELECT * FROM user"; RowMapper<User> rowMapper = new UserRowMapper(); // 定义一个RowMapper对象,用于将ResultSet转换为User对象 // 调用JdbcTemplate的query方法执行查询,并将结果集转换为List<User>对象 List<User> users = jdbcTemplate.query(sql, rowMapper); return users; } // 定义一个内部类,实现RowMapper接口,用于将ResultSet转换为User对象 private class UserRowMapper implements RowMapper<User> { @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setEmail(rs.getString("email")); return user; } } } ``` 在上面的示例中,我们定义了一个MyDao类,其中包含一个findAllUsers方法,用于查询所有用户数据并返回List<User>对象。在该方法中,我们使用JdbcTemplate的query方法执行查询,并将结果集转换为List<User>对象。为了将ResultSet转换为User对象,我们定义了一个内部类UserRowMapper,实现了RowMapper接口,用于将ResultSet中的数据映射到User对象中。最后,我们返回查询结果集的List对象

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值