The first section
Problems with traditional JDBC
1. The configuration information is hard coded. There are hard coding SQL statements and hard coding problems in PreparedStatement (where condition judgment) PreparedStatement 2. Frequently creating database connections wastes resources and affects performance. 3. When encapsulating the result set, there are many codes and large changes, which are difficult to maintain. // Load the database Driver class.forname (" com.mysql.jdbc.driver "); / / by driving for database connection connection = DriverManager. GetConnection (" JDBC: mysql: / / localhost: 3306 / mybatis? characterEncoding=utf-8", "root", "root"); String SQL = "select * from user where name =?" / / get a preparedstatement pretreatment preparedstatement object = connection. The prepareStatement (SQL); / / set the parameters, the first parameter to the number of parameters in the SQL statement (starting at 1), the second parameter for setting the values of the parameters / / issue SQL query is executed to the database, query result set out the resultSet = preparedStatement. ExecuteQuery (); Resultset.close (); preparedStatement.close(); connection.close();Copy the code
Problem solution
1. Create a database connection pool and obtain the connection from the pool. 2. Use the configuration file to pass parameters and data source configuration. 3. Use low-level techniques such as reflection and introspection to automatically map entities and tables to attributes and fields (POJO objects).Copy the code
In the second quarter
Related concepts of Mybatis
** OrM implements the Mapping of object-oriented programming languages to relational databases. When the ORM framework is mapped, programmers can take advantage of both the simplicity and ease of use of object-oriented programming languages and the technical benefits of relational databases. ORM wraps relational databases as an object-oriented model. ORM framework is an intermediate solution when the development of object-oriented design language and relational database is not synchronized. With ORM, applications no longer access the underlying database directly, but operate on persistent objects in an object-oriented manner, and the ORM framework translates these object-oriented operations into the underlying SQL operations. ORM framework to achieve the effect of saving, modifying, deleting persistent objects (POJOs) into database operations. Pojos :(Plain Old Java Objects) Pros: MyBatis is an excellent ORM-based semi-automatic lightweight persistence layer framework that supports customized SQL, stored procedures, and advanced mapping.Copy the code
In the third quarter
MyBatis quick start
Create a projectCopy the code
<dependencies> <! <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.6 < / version > < scope > runtime < / scope > < / dependency > <! <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <! Log4j </artifactId> log4j</artifactId> <version>1.2.12</version> </dependency> </dependencies> Create database tables and related entity classesCopy the code
Create configuration files SQLmapconfig. XML and usermapper.xmlCopy the code
Test: '//1.Resources utility class, config file loading, The configuration file to load the input stream into a byte InputStream resourceAsStream = Resources. The getResourceAsStream (" sqlMapConfig. XML "); //2. Constructor mode, parse configuration file, SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); / / 3. The factory pattern production sqlSession sqlSession sqlSession. = sqlSessionFactory openSession (); Select * from selectList; select * from selectOne; select * from selectOne; select * from selectOne; delete List<User> users = sqlSession.selectList("user.findAll"); for (User user : users) { System.out.println(user); } // Close the resource sqlsession.close (); `Copy the code
** add, delete and change **Copy the code
Sqlsession. insert(" namespace. Id ", entity object). ParameterType specifies the type of data to be inserted using the parameterType attribute in the mapping file. 2. The API used for the modification operation is SQLsession. update(" namespace. id ", entity object). 3. The API used for the deletion operation is sqlsession. delete(" namespace. id ",Object). 4. The transaction must be committed manually, sqlsession.com MIT ().Copy the code
The fourth quarter,
Core profile and mapping profile
** Mapping configuration file ** Namespace: ResultType: indicates the type of the returned value parameterType: indicates the type of the returned value. <select ID ="findByCondition" parameterType="user" resultType="user"> select * from user <where> <if test="id! =0"> and id=#{id} </if> <if test="username! <select id="findByIds" parameterType="list" resultType="user"> select * from User <where> <foreach collection="list" open="id in(" close=")" item="id" separator=","> #{id} </foreach> </where> </select>Copy the code
** Core configuration file ** Hierarchy:Copy the code
Enviroments labelCopy the code
There are two types of transactionManager: •JDBC: this configuration directly uses the commit and rollback Settings of JDBC and relies on connections from the data source to manage the transaction domain. •MANAGED: This configuration does almost nothing. It never commits or rolls back a connection, but lets the container manage the entire life cycle of the transaction (such as the context of the JEE application server). By default it closes the connection, however some containers do not want this, so you need to set the closeConnection property to false to prevent its default closing behavior. •UNPOOLED: the implementation of this dataSource simply opens and closes a connection each time it is requested. •POOLED: This data source implementation utilizes the concept of "pooling" to organize JDBC connection objects. •JNDI: This data source is implemented for use in a container such as an EJB or application server, which can centrally or externally configure the data source and then place a reference to the JNDI context. Mapper TAB, using the relative to the classpath resource references, such as: < mapper resource = "org/mybatis/builder/AuthorMapper. XML" / >, using a fully qualified resource locator (URL), such as: file:///var/mappers/AuthorMapper.xml < mapper url = "" / >, use the mapping interface implementation class's fully qualified class name, such as: < mapper class = "org. Mybatis. Builder. AuthorMapper" / >, all the mapping interface implementation within the package is registered as a mapping, such as: < package name = "org. Mybatis. Builder" / >Copy the code