봄 말 : (데이터베이스 JDBC 연결) JdbcTemplate을 객체

1. JdbcTemplate을 객체

  • 데이터베이스에 대한 연결이 봄 제공 JdbcTemplated org.springframework.jdbc.core.JdbcTemplate
  • 데이터베이스 패키지 dbutils를 제공에 dbutils.QueryRunner가 연결된
  • 두 개의 유사.

2. 개체 자체가 제공하는 데이터베이스의 JdbcTemplate

  • 데이터 소스의 JdbcTemplate 이것은 DriverManagerDataSource를 제조 할 수있다;
  • 메소드가 실행 된 SQL 명령문, 파라미터 값은 죽은 아닌 자리에 직접 기입 실행?
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 사용하여 XML 구성 접근 구성 데이터베이스

JdbcTemplateDemo1 죽은 작성하는 데이터베이스처럼하지 좋아해요

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

  • 이것은 또한 구성 데이터 소스 = 클래스는 "org.springframework.jdbc.datasource입니다. 이것은 DriverManagerDataSource
  • XML로 작성된 그냥 이것은 DriverManagerDataSource는 더 이상 클래스를 기록하지 않습니다.
<?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 조작 객체 (XML 데이터베이스 구성)

  • 수행 활동은 (여기에 자리를 쓰기? 그리고 QueryRunner (쿼리, 갱신) 같은, 그러나 동일한 방법 및 실행)
  • Spring은 제공 BeanPropertyRowMapper BeanListHandler, BeanHandler에서 dbutils.QueryRunner 유사를,
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 문

  • IAccountDao는 빈 객체를 얻어서, 점차적으로 데이터베이스의 실현 전화, 개체, 전화에 bean.xml를 주입하고있다;
  • 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}
    }
}

계정

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 문

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());
    }
}

반복 추출 코드 : 개인의 JdbcTemplate JdbcTemplate을 생략 할 수 있으며 및 집합 방법
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());
    }
}
게시 된 101 개 원래 기사 · 원의 찬양 (15) · 전망 6763

추천

출처blog.csdn.net/JH39456194/article/details/104440448