Spring中のJdbcTemplate

68152 ワード

JdbcTemplate概要
JdbcTemplateはspringフレームワークで提供されるオブジェクトであり、元のJdbc APIオブジェクトに対するシンプルなパッケージである.springフレームは多くの操作テンプレート類を提供してくれます.例えば、操作関係型データの:JdbcTemplate HbernaleTemplateなど、nosqlデータベースを操作している:Redis Templateなどの操作メッセージキューの:JmsTemplate
次に私達は口座の添削を例にとって、実例の説明を行います.まずこのような表を作成します.
create table account(id int primary key auto_increment,name varchar(20),money float);
次に二つのデータを挿入します.
insert into account values(null,"jack",1000),(null,"tina",1000);
関連するjarパッケージ座標をインポート
<packaging>jarpackaging>
    <dependencies>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.11version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.9version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.0.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.0.3.RELEASEversion>
        dependency>

    dependencies>
アカウントエンティティクラスを作成するAccount.java
package 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 +
                '}';
    }
}
アカウントDAOインターフェースの作成IAccountDao.java
package dao;

import domain.Account;

import java.util.List;

/**
 *         
 */
public interface IAccountDao {

    /**
     *     
     * @return
     */
    List<Account> findAllAccount();

    /**
     *   ID    
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     *   
     * @param account
     */
    int saveAccount(Account account);

    /**
     *   
     * @param account
     */
    int updateAccount(Account account);

    /**
     *   
     * @param acccountId
     */
    int deleteAccount(Integer acccountId);

    /**
     *         
     * @param accountName
     * @return               ,         null
     *                       
     */
    Account findAccountByName(String accountName);
}
DAO実現類の作成AccountDaoImpl.java
package dao.impl;

import dao.IAccountDao;
import 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;
    }

    public List<Account> findAllAccount() {
        String sql = "select * from account";
        List<Account> accounts = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
        return accounts;
    }

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

    public int saveAccount(Account account) {
        String sql = "insert into account values(?,?,?)";
        return jdbcTemplate.update(sql, account.getId(), account.getName(), account.getMoney());
    }

    public int updateAccount(Account account) {
        String sql = "update account set id=?,name=?,money=? where id=?";
        return jdbcTemplate.update(sql, account.getId(), account.getName(), account.getMoney(), account.getId());

    }

    public int deleteAccount(Integer acccountId) {
        String sql = "delete from account where id=?";
        return jdbcTemplate.update(sql, acccountId);
    }

    public Account findAccountByName(String accountName) {
        String sql = "select * from account where name=?";
        List<Account> accounts = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.size()>1)
        {
            throw new RuntimeException("        1");
        }
        if (accounts.isEmpty())
        {
            return null;
        }
        return accounts.get(0);
    }
}
アカウントを作成するServiceインターフェースIAccountService.java
package service;

import domain.Account;

import java.util.List;

public interface IAccountService {

    List<Account> findAllAccount();

    Account findAccountById(Integer accountId);

    int saveAccount(Account account);

    int updateAccount(Account account);

    int deleteAccount(Integer acccountId);

    Account findAccountByName(String accountName);

    boolean transformAccount(Account a1,Account a2,int money);
}
Service実現類の作成AccountServiceImpl.java
package service.impl;

import dao.IAccountDao;
import domain.Account;
import service.IAccountService;
import java.util.List;

public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    public int saveAccount(Account account) {
        return accountDao.saveAccount(account);
    }

    public int updateAccount(Account account) {
        return accountDao.updateAccount(account);
    }

    public int deleteAccount(Integer acccountId) {
        return accountDao.deleteAccount(acccountId);
    }

    public Account findAccountByName(String accountName) {
        return accountDao.findAccountByName(accountName);
    }

    /**
     *   
     * @param a1    
     * @param a2    
     * @param money     
     * @return
     */
    public boolean transformAccount(Account a1, Account a2, int money) {
        a1.setMoney(a1.getMoney()-money);
        a2.setMoney(a2.getMoney()+money);
        updateAccount(a1);
        updateAccount(a2);
        return true;
    }
}
springのプロファイルを作成する

<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="accountServiceImpl" class="service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDaoImpl">property>
    bean>

    
    <bean id="accountDaoImpl" class="dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate">property>
    bean>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver">property>
        <property name="url" value="jdbc:mysql://localhost:3306/class_db?useUnicode=true&serverTimezone=GMT&useSSL=false">property>
        <property name="username" value="root">property>
        <property name="password" value="qwe123">property>
        
        <property name="filters" value="stat" />
        
        <property name="maxActive" value="20" />
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />

        
        <property name="maxWait" value="60000" />

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        
        <property name="poolPreparedStatements" value="true" />
        <property name="maxOpenPreparedStatements" value="20" />
    bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource">property>
    bean>
beans>
テストコード
import domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IAccountService;

import java.util.List;

public class testdemo {

    private ApplicationContext ac;
    private IAccountService as;

    @Before
    public void init()
    {
        ac = new ClassPathXmlApplicationContext("bean.xml");
        as  = ac.getBean("accountServiceImpl", IAccountService.class);
    }

    @Test
    public void testFindall()
    {
        List<Account> allAccount = as.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindbyid()
    {
        Account accountById = as.findAccountById(1);
        System.out.println(accountById);
    }
    @Test
    public void testFindbyname()
    {
        Account jack = as.findAccountByName("jack");
        System.out.println(jack);
    }
    @Test
    public void testSave()
    {
        Account test = new Account();
        test.setName("test");
        test.setMoney(2000f);
        as.saveAccount(test);
    }
    @Test
    public void testUpdate()
    {
        Account account = as.findAccountById(10);
        account.setMoney(3000f);
        account.setName("test1");
        as.updateAccount(account);
    }
    @Test
    public void testDelete()
    {
        as.deleteAccount(10);
    }
    @Test
    public void testTransformaccount()
    {
        Account account1 = as.findAccountById(1);
        Account account2 = as.findAccountById(2);
        as.transformAccount(account1,account2,100);
    }
}
以上が今日共有したSpringのJdbcTemplateの添削についての使用です.皆さんに何か収穫がありますように、ご注目ください.