spring增删改查案例(用spring的内容和JdbcTemplate和Druid相关知识实现)

springIoc案例


一、第一步——配置jar包的坐标

<packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    </dependencies>

二、写包结构

在这里插入图片描述
并实现它的增删改查方法

public class AccountDaoImpl implements IAccountDao{
   

    private JdbcTemplate template;

    public void setTemplate(JdbcTemplate template) {
   
        this.template = template;
    }

    public List<Account> findAllAccount() {
   
        return template.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
    }

    public Account findAccountById(Integer id) {
   
        return template.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),id);
    }

    public void saveAccount(Account account) {
   
        template.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
    }

    public void updateAccount(Account account) {
   
        template.update("update account set name = ?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }

    public void deleteAccount(Integer id) {
   
        template.update("delete from account where id=?",id);
    }
}

三、搭建springIoc开发环境——编写xml文件

这种方式需要注意,在类中声明对象时,需要提供set方法。
例:

public class AccountServiceImpl implements IAccountService{
   

    private IAccountDao accountDao;

    //因为需要通过set方法注入,所以提供一个set方法

    public void setAccountDao(IAccountDao accountDao) {
   
        this.accountDao = accountDao;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值