Spring horse: JdbcTemplate objects (connecting to the database JDBC)

1. JdbcTemplate objects

  • JdbcTemplated a connection to the database is provided Spring org.springframework.jdbc.core.JdbcTemplate
  • dbutils.QueryRunner is connected to a database package provides dbutils
  • Similar two.

2. The database provided by the objects themselves JdbcTemplate

  • The data source may be prepared JdbcTemplate DriverManagerDataSource;
  • execute method executes SQL statements, parameter value is written directly to the dead, not a placeholder?.
JdbcTemplateDemo1
package com.jh.jdbctemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**JdbcTemplate的最基本用法*/
public class JdbcTemplateDemo1 {
    public static void main(String[] args) {
        //准备数据源
        DriverManagerDataSource ds=new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/maven?serverTimezone=GMT%2B8");
        ds.setUsername("root");
        ds.setPassword("jh7851192");
        //1.创建JdbcTemplate对象
        JdbcTemplate jt = new JdbcTemplate();
        //给jt设置数据源
        jt.setDataSource(ds);
        //2.执行操作
        jt.execute("insert into account(name,money)values ('ccc',1200)");
    }
}

3.JdbcTemplate using XML configuration approach configuration database

JdbcTemplateDemo1 do not like, like the database to write dead

JdbcTemplateDemo2
package com.jh.jdbctemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**JdbcTemplate的最基本用法
 * 采用XML配置的方法配置数据源,不用像JdbcTemplateDemo1一样把数据库写死
 * */
public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.获取bean对象JdbcTemplate
        JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作
        //execute 没有占位符?,直接写参数值
        jt.execute("insert into account(name,money)values ('ddd',2200)");
    }
}

bean.xml

  • This is also the configuration data source = class "The org.springframework.jdbc.datasource. The DriverManagerDataSource
  • Just DriverManagerDataSource written in xml, no longer writes class.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 配置账户的持久层-->
    <bean id="accountDao" class="com.jh.dao.impl.AccountDaoImpl">
        <!--注入JdbcTemplate对象-->
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        <!--<property name="dataSource" ref="dataSource"></property>-->
    </bean>
    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/maven?serverTimezone=GMT%2B8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="jh7851192"></property>
    </bean>
</beans>

4. JdbcTemplate CRUD operations objects (xml database configured)

  • Perform actions (here writing placeholders? And QueryRunner (query, update) the same, but not the same method and execute)
  • Spring provides a BeanPropertyRowMapper , similar to dbutils.QueryRunner in BeanListHandler, BeanHandler
JdbcTemplateDemo3
public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.获取bean对象JdbcTemplate
        JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作(这里写占位符? 和QueryRunner(query,update)一样,但是和execute方法不一样)
        /*//保存
        jt.update("insert into account(name,money)values (?,?)","eee",2345f);
        //更新
        jt.update("update account set name=?,money=? where id=?","jh2",2324f,6);
        //删除
        jt.update("delete from account where id=?",6);*/
        //查询所有
        //List<Account>accounts = jt.query("select * from account where money > ?",new AccountRowMapper(),1000f);
        /**Spring提供一个BeanPropertyRowMapper,类似于dbutils.QueryRunner中的BeanListHandler,BeanHandler
         * 以后不用自己写实现类:class AccountRowMapper*/
        /*List<Account>accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
        for (Account account:accounts){
            System.out.println(account);
            Account{id=1, name='aaa', money=4566.0}
            Account{id=5, name='jh', money=12213.0}
            Account{id=7, name='ddd', money=2200.0}
        }*/
        //查询一个
        List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
        System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
        //Account{id=1, name='aaa', money=4566.0}
        //查询返回一行一列(使用聚合函数,但不加group by子句)
        Long count = jt.queryForObject("select count(*) from account where money >?", Long.class, 1000f);
        System.out.println(count);//3
    }
}
//这是自己写的类AccountRowMapper
class AccountRowMapper implements RowMapper<Account>{
    /**
     * 把结果集中的数据封装到Account中,然后由Spring把每个Account加到集合中
     * */
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account=new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}

5. SQL statements written in the persistence layer

  • IAccountDao by getting the bean object, has been gradually injected bean.xml in the object, call, call the realization of the database;
  • accountDao—>jdbcTemplate—>dataSource
JdbcTemplateDemo4
public class JdbcTemplateDemo4 {
    public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        //2.获取bean对象
        IAccountDao accountDao=ac.getBean("accountDao",IAccountDao.class);
        //3.执行操作
        Account account = accountDao.findAccountById(2);
        System.out.println(account);//Account{id=1, name='aaa', money=4566.0}
        account.setMoney(1200f);
        accountDao.updateAccount(account);//下一次就更新为Account{id=1, name='aaa', money=1230.0}
    }
}

Account

package com.jh.domain;
import java.io.Serializable;
/**账户的实体类*/
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;

    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 Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

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

IAccountDao

package com.jh.dao;
import com.jh.domain.Account;
/**持久层*/
public interface IAccountDao {
    //根据id查询账户
    Account findAccountById(Integer accountId);
    //根据名称查询账户
    Account findAccountByName(String accountName);
    //更新账户
    void updateAccount(Account account);
}

SQL statement written in the persistence layer implementation class

package com.jh.dao.impl;
import com.jh.dao.IAccountDao;
import com.jh.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**持久层实现类*/
public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = jdbcTemplate.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.isEmpty()){
            return null;
        }if (accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

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

Repeat extraction Code: may be omitted private JdbcTemplate jdbcTemplate; and set methods
extends JdbcDaoSupport

package com.jh.dao.impl;
import com.jh.dao.IAccountDao;
import com.jh.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;
/**持久层实现类
 *抽取重复代码:可以省略private JdbcTemplate jdbcTemplate;和set方法
 * */
public class AccountDaoImpl2 extends JdbcDaoSupport implements IAccountDao {
    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.isEmpty()){
            return null;
        }if (accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}
Published 101 original articles · won praise 15 · views 6763

Guess you like

Origin blog.csdn.net/JH39456194/article/details/104440448