Spring中RowMapper接口在数据库中的作用

  • 在学习spring过程中,关于spring的数据库CRUD问题,和我们之前没有使用spring时写的CRUD语句变化不大
  • 使用RowMapper的接口就是用来把数据中的列字段和java Bean中的属性对应上,这样就可以赋值了。也像JDBC中的bean.setName(rs.getString(“name”);Spring把这段代码抽象出来写成RowMapper.
  • 下面来看一下具体怎么写(举一个例子来说明)

1.首先我们写一个实体类

package com.itheima.domain;

import lombok.Getter;
import lombok.Setter;

@Setter@Getter
public class Account {
    private Integer id;
    private String name;
    private Float money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

2.然后我们写一个AccountRowMapper类,把结果集中的数据封装到Account中,然后由Spring把每个Account加到集合中。

package com.itheima.jdbctemplate;

import com.itheima.domain.Account;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountRowMapper implements RowMapper<Account> {
    //把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
    public Account mapRow(ResultSet resultSet, int i) throws SQLException {
       Account account = new Account();
        account.setId(resultSet.getInt("id"));
        account.setName(resultSet.getString("name"));
        account.setMoney(resultSet.getFloat("money"));
        return account;
    }
}

3.然后我们在对数据库进行CRUD操作

package com.itheima.jdbctemplate;

import com.itheima.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


public class jdbctemplateDemo3 {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbctemplateDemo1",JdbcTemplate.class);
        //3.执行语句
        //保存
        //jdbcTemplate.update("insert into account(name,money)values(?,?)","eee",3333f);
        //更新
        //查询所有
        List<Account> accounts = jdbcTemplate.query("select * from account where money > ?",new AccountRowMapper(),1000f);
       for(Account account : accounts){
            System.out.println(account);
        }
        //查询一个
        //查询返回一行一列
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值