preface

The last article covered AOP technology, and in this article we’ll take a look at dao. In the last series of “Pony Mall”, we used the framework for accessing data for Mybatis, where we only need to write DAO interface to realize the operation of the database, so next we will understand how spring accesses the database.

DAO

DAO, Database Access Object data Access Object, using THE DAO mode, can be completely separated from data Access and storage, a good shielding of the differences of various databases.

Jdbc-based DAO implementation

Standard template for JDBC database operations

JdbcTemplate

Extract the above code up

public static Object query(String sql){ Connection conn = null; Statement stmt = null; List<Object> list = new LinkedList<>(); Try {class.forname (" com.mysql.jdbc.driver "); / / 2. Get the database connection conn = DriverManager. GetConnection (URL, NAME, PASSWORD); STMT = conn.createstatement (); //3. ResultSet rs = stmt.executeQuery(sql); // Select import java.sql.ResultSet; While (rs.next()) {// If there is data in the object, the loop prints list.add(rs); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { if (conn ! = null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } if (stmt ! = null) { try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } return list; } public static void main(String[] args) {query("select * from table"); }Copy the code

The JdbcTemplate code is actually a bit more complex, but the principle is still abstraction.There are roughly four types of JdbcTemplate:

  • A connection-oriented template approach. Connect to the database;
  • Statement-oriented template method, query statements;
  • Preparedstatement-oriented template method, dynamic splicing SQL statements, prevent SQL injection problems;
  • Template method for CallableStatement, stored procedure access.

In the Connection template approach, instead of creating a database Connection each time, we do this using a database Connection pooling technique. JDBC 2.0 standard introduces dataSource as the standard of database resource management. DataSource can adapt to different databases, as well as the number of database connections, release and other functions, any ORM framework will integrate with it

ORM framework Spring is integrated with MyBatis

Data query using Mybatis alone

// Configuration file Configuration = new Configuration(); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); / / access to connect to the database sqlSession sqlSession sqlSession. = sqlSessionFactory openSession (); List<Object> list = sqlSession.selectList("select * from table"); sqlSession.close();Copy the code

When spring and Mybatis integrate, inject database information into dataSource through IOC container, sqlSessionFactory obtains SqlSession from dataSource, and then execute SQL statement. In the DAO interface written by us, @mapper generates the proxy class to become the bean of Spring. When we access the interface, the proxy class first obtains SqlSession, then calls the interface method, executes the corresponding SQL statement, and converts the data back to the entity defined by us.Load the MapperScannerRegistrar processor

// like spring's beanFactory, the dao is registered, the bean information is parsed, and the proxy class MapperScannerRegistrar#registerBeanDefinitions is generatedCopy the code

Here is a brief introduction to spring and Mybatis integration

Transaction with AOP

The transaction

We typically place transactions in the Service layer and data processing in the DAO layer, and use the logic of the Service layer to decide whether the transaction is committed or rolled back. This design pattern once again reflects the spring framework’s idea of each class doing its job.

practice

The Transactional annotation makes it possible to automatically commit a method transaction, referring to the AOP techniques of our last article. Without looking at the code, let’s imagine managing transactions through AOP.

Any Transactional annotation with the @around annotation goes to the AOP method @around to open a transaction execution. SQL commits a transaction catch a transaction rollbackCopy the code

TransactionAspectSupport#invokeWithinTransaction Spring transaction delivery, if the current transaction, will not start the transaction.

private static final ThreadLocal<Map<Object, Object>> resources =
			new NamedThreadLocal<>("Transactional resources");
Copy the code

Transaction start, and commit. The proceedWithInvocation method for target execution

summary

Through the simple explanation of this article, we have a basic understanding of Spring access to the database, if you want to further understand the need to read the source code, the source code method on the English annotations are basically explained the use of the method, and then can be combined with online tutorials continue to in-depth. When looking at spring source code, don’t worry about not understanding it. We can use the DEBUgger mode of IDEA to debug step by step and find the call relationship of methods to find the knowledge we need.