Preface
Every time I open the learning video to watch, I always want to organize and record it in the future, but there are always some big and small reasons (well, only lazy) that cause this wonderful dream to be broken. Ha-ha, I don't know what kind of mood trend it is today. I opened it and wrote this sentence, but I hope I can really keep it up. Before I started writing, I thought about whether the content of the articles would be too simple. There are too many big guys in the platform. I often feel like I'm not a beginner yet. However, publishing these articles is actually just to record my growth. I think it doesn't matter if I think about it here. The knowledge is too shallow. I hope you can give me more advice.
Tip: This article introduces you to some of the things that get you started with MyBatis, and the following is the body of this article
I. Introduction to MyBatis
1. Problems with the original JDBC:
- The database frequently creates and releases connections, which wastes resources and affects system performance.
- Sql statements are hard-coded in the code, which is unsuitable for maintenance, but there is a greater possibility that SQL statements will change in the actual development.
- When querying, the results need to be encapsulated manually. When inserting, entity data needs to be manually set to a placeholder position.
2. Solution:
- Initialize connection resources using database connection pool
- Extract Sql statement into xml configuration file
- Automatically map entity attributes to table fields using underlying technologies such as reflection and Introspection
3. What is MyBatis?
We can all use MyBatis to solve the problems described above
MyBatis is a java-based, persistent framework that features the following:
- JDBC is encapsulated internally.
- Hide the clutter of API s in JDBC
- Developers just need to focus on sql statements
- Configuring by XML or annotation
- Solve the problem of entity-database mapping with orm automation
We can learn more from the website:
mybatis: http://www.mybatis.org/mybatis-3.
2. Development Steps
1. Add MyBatis coordinates
1. Import mysql database driver
The code is as follows (example):
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>version number</version> </dependency>
2. Import MyBatis coordinates
The code is as follows (example):
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>version number</version> </dependency>
2. Creating database tables
3. Writing Entity Classes
4. Mapper.xml mapping file
1. Map file constraint header:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
2,namespace:
Namespace, which names the current mapper and, together with the id of the statement below, forms the identity of the query by calling the mapper method directly using the Namespace Name. Method Name
<mapper namespace="Name">
3, < mapper > Configuration
Namespace, which names the current mapper and, together with the id of the statement below, forms the identity of the query by calling the mapper method directly using the Namespace Name. Method Name
<mapper> <select id="name" resultType="Entity type corresponding to query result"> To execute sql Sentence </select>//You need to switch labels when performing other operations, such as insert, update, delete </mapper>
5. Core file MapConfig.xml
1. MyBatis Core File Constraint Header:
Namespace, which names the current mapper and, together with the id of the statement below, forms the identity of the query by calling the mapper method directly using the Namespace Name. Method Name
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
2. Mybatis Core File Configuration
Namespace, which names the current mapper and, together with the id of the statement below, forms the identity of the query by calling the mapper method directly using the Namespace Name. Method Name
<configuration> //Data Source Environment <!--default="development": Specify the default environment name--> <environments default="development"> <!--id="development": Specify the current environment name--> <environment id="development"> <transactionManager type="JDBC"/>//Transaction Manager <!--type="POOLED": Specifies that the current data source type is a connection pool--> <dataSource type="POOLED">//data source <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> //Load Mapping File <mappers> <mapper resource="mapper Profile Location"></mapper> </mappers> </configuration>
6. Test Classes
//Load Core Profile InputStream resourceAsStream = Resources.getResourceAsStream("Core Profile.xml"); //Get sqlSession Factory Object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); //Get sqlSession object SqlSession sqlSession = sqlSessionFactory.openSession(); //Execute sql statement //param("namespace+id") List<User> userList = sqlSession.selectList("namespace.id");//query sqlSession.id name("namespace.id",Entity Object)//Change sqlSession.delete("namespace.id",Object)//delete //Print results System.out.println(userList); //Release Resources sqlSession.close();
3. Examination of the Additions and Deletions of MyBatis
1. Query operation
List<User> userList = sqlSession.selectList("userMapper.findAll");
sql Sentence <select id="findAll" parameterType="Type of data to query" resultType="BsHolidaySetUpResult"> select * from User </select>
2. New operations
sqlSession.insert("userMapper.add", user);
sql Sentence <!--When adding operations, values The value in parameterType Property name in class--> <insert id="insert" parameterType="Type of data to insert"> insert into user values(#{id},#{username},#{password},#{Entity Attribute Name}) </insert>
3. Delete Operation
sqlSession.delete("userMapper.delete",3);
sql Sentence <!--Delete data based on a field. parameterType For this field type--> <!--When passing a single parameter, you can use#How {Any String} --> <delete id="delete" parameterType="java.long.Integer"> delete from user where id=#{Any string} </delete>
4. Modification
sqlSession.update("userMapper.update", user);
sql Sentence <update id="update" parameterType="Type of data to modify"> update user set username=#{username},password=#{password} where id=#{id} </update> <!--mybatis When performing an update operation, you need to commit the transaction manually, that is, when performing an add-delete operation, you commit the transaction to implement the corresponding operation--> sqlSession.commit();
IV. MyBatis Core Profile
1. Hierarchical Relations
- configuration Configuration
- properties attribute
- Settings settings
- TypeeAllases type alias
- TypeeHandlers Type Processor
- objectFactory object factory
- plugins plugin
- environments environment
- Environment environment variable
- transactionManager Transaction Manager
- dataSource data source
- Environment environment variable
- Database vendor identification for databaseidProvider
- mappers mapper
2. Analysis of Common Configurations for Test Classes
1. Environment Label
This tag is primarily used for configuring the data source environment
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments>
There are two types of transaction manager:
- JDBC uses JDBC's commit and rollback settings directly and relies on connection connections to manage transaction scopes
- MANAGED uses containers to manage the entire life cycle of a transaction. Connection connections are closed by default, and the closeConnection property needs to be set to false to prevent closing.
There are three types of data sources:
- UNPOOLED: The implementation of this data source is to open and close the connection each time it is requested
- POOLED: This implementation of data sources uses the concept of pools to organize JDBC connection objects.
- JNDI: This data source is implemented to be used in containers such as EJB s or application servers, which can centralize or externally configure the data source and place a reference to the JNDI context.
2. mappers Tags
This tag loads maps in several ways:
- Use resource references relative to class paths
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
- Use fully qualified resource locators (urls)
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
- Implement fully qualified class names for classes using mapper interfaces
<mapper class="org.mybatis.builder.AuthorMapper"/>
- Register all mapper interface implementations within the package as mappers
<package name="org.mybatis.builder"/>
3. Properrties Label
This tag can load additional configured properties files
<properties resourse="jdbc.properties"></properties>
3. typeAliases tag
This tag is used to customize the alias
<typeAliases> <typeAlias type="Original name" alias="alias"/> </typeAliases>
Aliases of common types set by the mybatis framework
data type | alias |
---|---|
String | string |
Long | long |
Integer | int |
Double | double |
Boolean | boolean |
4. Corresponding API s for MyBatis
1. SqlSessionFactoryBuilder
Common API s: SqlSessionFactory.build(InputStream inputStream)
Build a SqlSessionFactory object by loading the input stream of mybatis's core file
String resource = "org/mybatis/builder/mybatis-config.xml"; InputStream inputStream = ResourceAsStream(resource); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(inputStream);
The Resources tool class, which is in the org.apache.ibatis.io package, helps you load resource files from the class path, file system, or a web URL.
SqlSessionFactory has several methods for creating SqlSession instances. There are two commonly used:
Method | explain |
---|---|
openSession() | A transaction is opened by default, but it does not commit automatically, which means that the transaction needs to be committed manually before updating operational data can be persisted to the database |
openSession(boolean autoCommit) | The parameter is whether to commit automatically, and if set to true, you do not need to commit the transaction manually |
2. SqlSession Session Object
The SqlSession instance is a very powerful class in MyBatis. Includes all methods for executing statements, committing or rolling back transactions, and getting mapper instances.
The main ways to execute a statement are:
<T> T selectOne(String statement,Object parameter) <E> List<E> selectList(String statement,Object parameter) int insert(String statement,Object parameter) int update(String statement,Object parameter) int delete(String statement,Object parameter)
The main ways to operate transactions are:
void commit() void rollback()