cool hit counter SSH framework tour-spring (3)_Intefrankly

SSH framework tour-spring (3)


spring.jpg

1.Spring's jdbcTemplate operations


The Spring framework is a one-stop framework for the three-tier structure of JavaEE, with technologies that address each layer, using jdbcTempalte at the DAO (data operations layer). And Spring is also a glue-based framework for third-party frameworks also has good integration support for different persistence layer technologies are encapsulated.

ORM Persistence Technology

Template category

JDBC

org.springframework.core.JdbcTemplate

Hibernate5.x

org.springframework.hibernate5.HibernateTemplate

IBatis(MyBatis)

org.springframework.orm.ibatis.sqlMapClientTemplate

JPA

org.springframework.orm.jpa.JpaTemplate

The following are Spring's CURD operations on the database.

1.1 Preparation

Spring encapsulates jdbc, so you need to import it on top of the previous Spring jar package spring-jdbc.jar harmony spring-tx.jar package, plus remember to import the driver package for the database.

Creating databases and data tables, the JdbcTemplate in Spring just wraps Jdbc and does not automatically create data tables for us

Data Table Structure.png

physical category

package cc.wenshixin.jdbc;

public class Student {
    private int id;
    private String name;
    private String sex;
    
    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", sex=" + sex + "]";
    }
}

Adding, deleting, and changing operations are all calls to update() method, Spring overloads a number of update() Methods.

1.2 Adding operations

    @Test
     // Add operation
    public void add()
    {
         // Set database information
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        
         // Create the jdbcTemplate object and set the data source
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
         // Call the methods inside the JdbcTemplate object to implement the operation
        String sql = "INSERT INTO student(name,sex) VALUES(?,?)";
        int rows = jdbcTemplate.update(sql, " Simon", " male");
        System.out.println(rows);
    }

1.3 Delete operation

    @Test
     //delete operation
    public void delete()
    {
         // Set database information
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        
         // Create the jdbcTemplate object and set the data source
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
         // Call the methods inside the JdbcTemplate object to implement the operation
        String sql = "DELETE FROM student WHERE id=?";
        int rows = jdbcTemplate.update(sql, 2);
        System.out.println(rows);
    }

1.4 Modifying operations

    @Test
     // Modify the operation
    public void update()
    {
         // Set database information
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        
         // Create the jdbcTemplate object and set the data source
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
         // Call the methods inside the JdbcTemplate object to implement the operation
        String sql = "UPDATE student SET name=? WHERE id=?";
        int rows = jdbcTemplate.update(sql, " Zhang Xiao", 2);
        System.out.println(rows);
    }

1.5 Query operations

basic jdbc query operations. will , although the use of frameworks will not use this base code, but when frameworks are not available, the base methods can be used to implement.

    // Basic steps to manipulate a database using jdbc
    @Test
    public void testJdbc() throws SQLException
    {
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        
        try {
             // Load the driver
            Class.forName("com.mysql.jdbc.Driver");
             // Create a connection
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false", "root", "root");
             // Write sql statements
            String sql = "SELECT * FROM student WHERE id=?";
             // Pre-compiled sql
            psmt = conn.prepareStatement(sql);
             // Set parameters
            psmt.setInt(1, 1);
             //execute sql
            rs = psmt.executeQuery();
             // traversing the result set
            while(rs.next())
            {
                 // return the result set obtained
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String sex = rs.getString("sex");
                 // Put in the object
                Student student = new Student();
                student.setId(id);
                student.setName(name);
                student.setSex(sex);
                System.out.println(student);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if(rs != null)
            {
                rs.close();
            }
            if(psmt != null)
            {
                psmt.close();
            }
            if(conn != null)
            {
                conn.close();
            }
        }
    }
  • Number of queries

Query quantity using queryForObject() Methods.

@Test
     // Query quantity operations
    public void queryCount()
    {
         // Set database information
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        
         // Create the jdbcTemplate object and set the data source
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
         // Call the methods inside the JdbcTemplate object to implement the operation
        String sql = "SELECT COUNT(id) FROM student";
        int count = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(count);
    }

When querying an object, To achieve first physical category The query implements the Spring Query Interface RowMapper implementation class.

Query interface implementation class for entity classes

package cc.wenshixin.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

public class StudentRowMapper implements RowMapper<Student>{

    @Override
    public Student mapRow(ResultSet rs, int num) throws SQLException {
        // Data obtained from the result set
        int id = rs.getInt("id");
        String name = rs.getString("name");
        String sex = rs.getString("sex");
        
        // classifier for objects with a handle The result obtained is encapsulated inside the object
        Student student = new Student();
        student.setId(id);
        student.setName(name);
        student.setSex(sex);
        
        return student;
    }   
}
  • Querying a single object
    @Test
     // Query individual object operations
    public void queryObject()
    {
         // Set database information
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        
         // Create the jdbcTemplate object and set the data source
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
         // Call the methods inside the JdbcTemplate object to implement the operation
        String sql = "SELECT * FROM student WHERE id=?";
        Student student = jdbcTemplate.queryForObject(sql, new StudentRowMapper(), 1);
        System.out.println(student.toString());
    }

Querying multiple objects

    @Test
    // Querying multiple objects operations
    public void queryList()
    {
         // Set database information
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        
         // Create the jdbcTemplate object and set the data source
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
         // Call the methods inside the JdbcTemplate object to implement the operation
        String sql = "SELECT * FROM student";
        List<Student> studentList = jdbcTemplate.query(sql, new StudentRowMapper());
        System.out.println(studentList);
    }

2.Spring configure connection pool


do jdbc operating hours, Not always connect to the database, Mostly create a database connection pool, Each time a connection is made to this database connection pool fetch the connection object in, Reduction of database connections harmony Operation of the release。

2.1 Preparation

The first step is to import configure c3p0 connection pool of jar packet,c3p0.jar harmony mchange.jar Download Address, Then create Spring of configuration file。

2.2 configure connection pool

Taking the above student physical category as an example, pass (a bill or inspection) service kind,dao kind, Insert a piece of data。

configuration file

property to inject database configuration information and properties of the jdbcTemplate.

<?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:aop="http://www.springframework.org/schema/aop"
    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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  <!--  configurec3p0 connection pool -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--  Injecting property values -->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useSSL=false"></property>
    <property name="user" value=""></property>
    <property name="password" value=""></property>
  </bean>
  
  <!--  Configuring the creation of objects -->
  <bean id="studentService" class="cc.wenshixin.service.StudentService"></bean>
  <bean id="studentDao" class="cc.wenshixin.dao.StudentDao"></bean>
  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--  classifier for objects with a handledataSource Pass inside the template object -->
    <property name="dataSource" ref="dataSource"></property>
  </bean>
  
  <!--  Turn on annotation scanning -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
</beans>

DAO Class

package cc.wenshixin.dao;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;

public class StudentDao {
    @Resource(name="jdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    
    // Insert data
    public void add()
    {
        String sql = "INSERT INTO student(name,sex) VALUES(?,?)";
        jdbcTemplate.update(sql," old king"," male");
    }
}

Service Class

package cc.wenshixin.service;

import javax.annotation.Resource;

import cc.wenshixin.dao.StudentDao;

public class StudentService {
    @Resource(name="studentDao")
    private StudentDao studentDao;
    
     // Add operation
    public void add()
    {
        studentDao.add();
    }
}

Test category

package cc.wenshixin.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cc.wenshixin.service.StudentService;

public class TestC3p0 {
    @Test
    public void test1()
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        StudentService service = (StudentService) context.getBean("studentService");
        service.add();
    }
}

3.Spring Transaction Management


3.1 Basic concepts of transactions

A transaction is a logical set of operations, and the individual logical units that make up the set either succeed together or fail together.

Characteristics of the transaction.

  • Atomicity: emphasizing that matters are indivisible
  • Consistency: the integrity of data before and after the execution of a transaction remains consistent
  • Isolation: a transaction should not receive interference from other transactions during its execution
  • Persistence: once the transaction is completed, the data persists to the database

If the security issues raised by isolation are not taken into account.

  • Dirty read: one transaction reads the uncommitted data of another transaction
  • Non-repeatable reads: one transaction reads an update that has been committed by another transaction resulting in inconsistent results for multiple queries
  • False read: one transaction reads the insert data that has been committed by another transaction resulting in inconsistent results for multiple queries

Solving the read problem: setting the isolation level of the transaction

  • Uncommitted reads: dirty reads, non-repeatable reads, and dummy reads can all occur
  • Committed reads: avoid dirty reads, but non-repeatable and dummy reads can occur
  • Repeatable reads: avoid dirty and non-repeatable reads, but dummy reads can happen
  • Serialization: avoiding all the above read problems

Addendum: The default transaction isolation level for Mysql databases is repeatable reads.

3.2 API for Spring transaction management

Spring There are two ways to manage transactions, One type of programmatic transaction management, non-use, Alternative Declarative Transaction Management, due toxml configuration file realize harmony Annotation-based implementation。

Interface to the Spring Platform Transaction Manager PlatformTransactionManager, for different DAO The framework of the layer provides interfaces different implementation class.

Transaction Manager interface implementation class

Applicable framework

org.springframework.jdbc.datasource.DataSourceTransactionManager

Use when using Spring JDBC or IBatis for persistent data

org.springframework.orm.hibernate3.HibernateTransactionManager

When using the Hibernate 5.x version for persistent data use the

The following is an example of a bank transfer to illustrate the use of the Spring API

Create a data table and add data for two experiments

Initial data.png

DAO Class

package cc.wenshixin.dao;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;

public class DealDao {
    @Resource(name="jdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    
    public void subMoney(String name, int money)
    {
        String sql = "UPDATE yinhang SET money=money-? WHERE name=?";
        jdbcTemplate.update(sql, money, name);
    }
    
    public void addMoney(String name, int money)
    {
        String sql = "UPDATE yinhang SET money=money+? WHERE name=?";
        jdbcTemplate.update(sql, money, name);
    }
}

Service Class

package cc.wenshixin.service;

import javax.annotation.Resource;

import cc.wenshixin.dao.DealDao;

public class DealService {
    @Resource(name="dealDao")
    private DealDao dealDao;
    
    public void deal()
    {
         // Xiao Ming transferred 1000 yuan to Xiao He
        dealDao.subMoney(" Simon", 1000);
        dealDao.addMoney(" blackish", 1000);
    }
}

xml configuration file

<?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:aop="http://www.springframework.org/schema/aop"
    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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  <!--  Configuring Database Information -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--  Injecting property values -->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useSSL=false"></property>
    <property name="user" value=""></property>
    <property name="password" value=""></property>
  </bean>
  
  <!--  Configuration objects -->
  <bean id="dealService" class="cc.wenshixin.service.DealService"></bean>
  <bean id="dealDao" class="cc.wenshixin.dao.DealDao"></bean>
  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--  classifier for objects with a handledataSource Pass inside the template object -->
    <property name="dataSource" ref="dataSource"></property>
  </bean>
  
  <!--  Turn on annotation scanning -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
</beans>

Test category

package cc.wenshixin.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cc.wenshixin.service.DealService;

public class DealTest {
    @Test
    public void test()
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        DealService dealService = (DealService) context.getBean("dealService");
        dealService.deal();
    }
}

No abnormalities generated, result is normal

No abnormal results.png

The following simulates the occurrence of an abnormal situation, where the actual situation is that the banking system has gone wrong, the network is down, etc.

(located) at Service Class Add the following code to the:

     // Xiao Ming transferred 1000 yuan to Xiao He
    dealDao.subMoney(" Simon", 1000);
     int i = 10 / 0;  //Simulation of anomalies
    dealDao.addMoney(" blackish", 1000);

Execute the result again with a divide by 0 exception, but the database results in

Simulation of abnormal results.png

Simon less1000 primary, But because of the unusual, blackish There was no increase in1000 primary, This is definitely not going to work., Exceptions require a transaction rollback。

will configuration file Change it to the following configuration file, Compared to the above configuration file, Binding of transactions added harmony Transaction Manager's configure, In addition, add to the class where the method to use the transaction is located the @Transactional This does not affect the result, but it is better to add it for code maintenance.

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
  <!--  Configuring Database Information -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!--  Injecting property values -->
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useSSL=false"></property>
    <property name="user" value=""></property>
    <property name="password" value=""></property>
  </bean>
  
  <!--  Configuration objects -->
  <bean id="dealService" class="cc.wenshixin.service.DealService"></bean>
  <bean id="dealDao" class="cc.wenshixin.dao.DealDao"></bean>
  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--  classifier for objects with a handledataSource Pass inside the template object -->
    <property name="dataSource" ref="dataSource"></property>
  </bean>
  
  <!--  Turn on annotation scanning -->
  <context:component-scan base-package="cc.wenshixin"></context:component-scan>
    
  <!--  configure transaction manager -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     empty intodataSource
    <property name="dataSource" ref="dataSource"></property>
  </bean>
  
  <!--  configure Transaction Enhancements -->
  <tx:advice id="txadvice" transaction-manager="transactionManager">
    <!--  transactional -->
    <tx:attributes>
      <!--  Set the method matching rules for performing transaction operations -->
      <tx:method name="deal*" propagation="REQUIRED"/>
    </tx:attributes>
  </tx:advice>
  
  <!--  configure tangent plane (math.) -->
  <aop:config>
    <!--  entry point -->
    <aop:pointcut expression="execution(* cc.wenshixin.service.DealService.*(..))" id="pointcut"/>
    <!--  tangent plane (math.) -->
    <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut"/>
  </aop:config>
</beans>

Execute it again with an exception, but the database result does not change.


Recommended>>
1、Suzhou Industrial Park to create an artificial intelligence industry gathering area
2、Star Chart Data 2018 Double Eleven All Online Shopping Big Data Analysis Report
3、Extra Extra Handan also has a national youth electronic information science and innovation education base
4、Major Indian shipping company partners with IBM to launch blockchain platform and much more
5、KNIME a powerful open source data mining software platform

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    Contact US

    Welcome to Intefrankly.

    Intefrankly is a platform that you can show your opnions related to IT technology, and communicates to the people who interested in IT and Artificial Intelligence area.