CRUD Using spring Dependency Injection

Steps:

  1. Establishment of database tables
  2. Introducing dependency
  3. Create an entity class domain
  4. Create dao layer, create dao interface and implementation class
  5. Create service layer, create service interface and implementation class
  6. Write configuration files
  7. Test class

Code example:

1. Database tables
Take three columns of example ID name money

2. Introducing dependencies are sql spring junit dbuntils c3p0, respectively

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.cfg</groupId>
    <artifactId>spring_day02_crud</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--Introducing dependency-->
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>

        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>

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

</project>

3. Create entity classes (under the domain package) Account and get set

package cn.cfg.domain;

public class Account {
    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 +
                '}';
    }
}

4. Create dao interfaces and implementation classes

dao interface

package cn.cfg.dao;

import cn.cfg.domain.Account;
import org.apache.commons.dbutils.QueryRunner;

import java.util.List;

public interface AccountDao{
//    Check all
    public List<Account> findAll();
//    According to id check
    public Account findById(Integer id);
    //Add to
    public void save(Account account);
    //change
    public void update(Account account);
    //delete
    public void del(Integer id);
}

dao interface implementation class AccountDaoImpl

package cn.cfg.dao.impl;

import cn.cfg.dao.AccountDao;
import cn.cfg.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

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

public class AccountDaoImpl implements AccountDao {
    QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    public List<Account> findAll() {
        String sql="select * from account";
        try {
            List<Account> list = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
//According to id check
    public Account findById(Integer id) {
        String sql="select * from account where id=?";
        try {
            Account account = queryRunner.query(sql, new BeanHandler<Account>(Account.class), id);
            return account;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //Preservation
    public void save(Account account) {
        String sql="insert into account values(null,?,?)";
        try {
            queryRunner.update(sql,account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //Change according to id
    public void update(Account account) {
        String sql="update account set name=?,money=? where id=?";
        try {
            queryRunner.update(sql,account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
//Delete by id
    public void del(Integer id) {
        String sql="delete from account where id=?";
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

5. Create service interfaces and implementation classes

service interface

package cn.cfg.service;

import cn.cfg.domain.Account;

import java.util.List;

public interface AccountService {
    //    Check all
    public List<Account> findAll();
    //    According to id check
    public Account findById(Integer id);
    //Add to
    public void save(Account account);
    //change
    public void update(Account account);
    //delete
    public void del(Integer id);
}

service implementation class
package cn.cfg.service.impl;

import cn.cfg.dao.AccountDao;
import cn.cfg.domain.Account;
import cn.cfg.service.AccountService;

import java.util.List;

public class AccountServiceImpl implements AccountService {
AccountDao accountDao;

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

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

public Account findById(Integer id) {

    return accountDao.findById(id);
}

public void save(Account account) {
    accountDao.save(account);
}

public void update(Account account) {
    accountDao.update(account);
}

public void del(Integer id) {
    accountDao.del(id);
}
}

6. Write configuration files
First, jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.user=root
jdbc.password=root

The core configuration file applationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--The test class needs to be invoked service afferent dao-->
    <bean id="accountService" class="cn.cfg.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    
    <!--to accountDao In the layer queryRunner dateSource Value transfer configuration -->
    <bean id="accountDao" class="cn.cfg.dao.impl.AccountDaoImpl">
        <property name="queryRunner" ref="queryRunner"></property>
    </bean>
    
    <!--Here qureyRunner Transfer to 14 rows ref Medium queryRunner
        The following values are passed in constructor mode instead of in use set Method 
         Because in daoImpl in queryRunner It exists in the form of constructors.
    -->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg type="javax.sql.DataSource" ref="dateSource"></constructor-arg>
    </bean>
    
    <!--dateSource Pass-by reference jdbc.properties Data in-->
    <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    
    <!--Introduce jdbc.properties file-->
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>

</beans>

7. test class

package cn.cfg;

import cn.cfg.domain.Account;
import cn.cfg.service.AccountService;
import cn.cfg.service.impl.AccountServiceImpl;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestCRUD {
//    Query all
    @Test
    public void testFindAll(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        List<Account> all = accountService.findAll();
        for (Account aa:all){
            System.out.println(aa);
        }
    }
//      Query by id
    @Test
    public void testFindById(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);
        Account account = accountService.findById(2);
        System.out.println(account);
    }
//    Add save
    @Test
    public void testSave(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applationContext.xml");
        AccountService accountService = ac.getBean("accountService", AccountService.class);

        Account account = new Account();
        account.setName("Li Si");
        account.setId(null);
        account.setMoney(1999888F);

        accountService.save(account);
    }

    //Delete the newly added Li Si
    @Test
    public void testDel(){
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applationContext.xml");
        AccountServiceImpl accountService = ac.getBean("accountService", AccountServiceImpl.class);

        accountService.del(4);

    }


}

Add success effect:

Delete success effect:

Tags: JDBC SQL Apache xml

Posted on Sun, 06 Oct 2019 05:37:09 -0700 by icarpenter