preface
MyBatis is an excellent persistence layer framework, a semi-ORM (Object relational mapping) framework, it supports customized SQL, stored procedures and advanced projection. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can use simple XML or annotations to configure and map native types, interfaces, and Java’s Plain Old Java Objects (POJOs) to records in the database.
The role of MyBatis
MyBatis function is in the persistence layer that is to access the database operation, we used to access the database is to use JDBC to access the database,JDBC access to the database need to write a lot of repeated code, if the database access a lot of database also need to continue to open the connection and close the connection, very consumption of system performance MyBatis encapsulates the JDBC underlying access to the database code, let us program ape only need to care about how to write a good SQL, not need to write JDBC underlying code
Advantages and disadvantages of MyBatis
advantages
- MyBatis encapsulates the details of JBDC’s low-level access to the database so that we can access the database without having to deal with the JDBC API
- MyBatis simple and easy to learn, program ape directly write SQL statements, suitable for SQL statement performance requirements of the project is relatively high
- SQL statements are encapsulated in configuration files, which facilitates unified management and maintenance and reduces the coupling degree of programs
- SQL code is completely separated from program code and can be reused
- Dynamic SQL tags are provided to support writing dynamic SQL
- Provides mapping labels to support ORM field relational mapping of objects to databases
disadvantages
- Too much reliance on SQL statements leads to poor database portability and database replacement. If SQL statements are different, the WORKLOAD of SQL statements is heavy
- Methods in daOs do not support method overloading because tag ids in XML must be unique
MyBatis configuration file
The properties element
The properties element describes all externalizations. Alternative properties are typically used to configure the connection data source, either using the property child node or resource path reference
Use the property child node for configuration
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</properties>
Copy the code
Use resource path references
<properties resource="jdbcConfig.properties"/>
Copy the code
Properties in jdbcconfig. properties
. Driver = com. Mysql. JDBC driver url = JDBC: mysql: / / 127.0.0.1:3306 / test the username = root password = 123456Copy the code
Configuration to connect data sources
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
Copy the code
If the property child is used to configure and use resource path references, which will MyBatis call? MyBatis calls the property value of the resource path reference because the resource path reference takes precedence over the property child node
Settings elements
Settings are the most important adjustment Settings in MyBatis. They change the runtime behavior of MyBatis
<settings> <! Setting name="cacheEnabled" value="true"/> <! <setting name="lazyLoadingEnabled" value="true"/> <! <setting name=" Introduction to the slogs "value="false"/> <! - for unknown SQL queries, allowed to return to a different result sets in order to achieve the effect of general - > < setting name = "multipleResultSetsEnabled" value = "true" / > <! <setting name="useColumnLabel" value="true"/> <! Setting name="useGeneratedKeys" value="true"/> <! <setting name="autoMappingBehavior" value="FULL"/> <! <setting name="defaultExecutorType" value="BATCH"/> <! <setting name="defaultStatementTimeout" value="25000"/> </ Settings >Copy the code
TypeAliases elements
The typeAliases element aliases javabeans for use in the Mappeer configuration file
When we get a JavaBean from a Mapper configuration file without aliasing it, we need to get the full path of the project in which the JavaBean resides
<! <select id="login" resultType="cn.friday.pojo.DevUser"> select * FROM dev_user WHERE devCode=#{devCode} AND devPassword=#{devPassword} </select>Copy the code
Next we’ll alias the JavaBean
<typeAliases>
<typeAlias type="cn.friday.pojo.DevUser" alias="devUser"/>
<typeAlias type="cn.friday.pojo.AppInfo" alias="appInfo"/>
</typeAliases>
Copy the code
MyBatis will automatically scan all javabeans in the specified package and give them a default alias. MyBatis will automatically scan all Javabeans in the specified package and give them a default alias Name, the default alias is the JavaBean name, as shown below
<typeAliases>
<package name="cn.friday.pojo"/>
</typeAliases>
Copy the code
Mapper configuration files can normally use JavaBean alias, do not need to obtain the full path of the JavaBean
<! <select id="login" resultType="DevUser"> select * FROM dev_user WHERE devCode=#{devCode} AND devPassword=#{devPassword} </select>Copy the code
Environments elements
MyBatis can be configured with a variety of environments, such as development environment, test environment, production environment, etc. We can flexibly choose different configurations, so as to apply SQL mapping to different database environments. These different operating environments can be configured using the Environments element
Environments Element Configuration of elements
<! -- Development environment --> <! -- The default property indicates the data source we will enable by default --> <environments default="development"> <! --> <environment id="development"> <! <transactionManager type="JDBC"/> <! <dataSource type="POOLED"> <property name="driver" value=" com.mysql.jdbc.driver "/> <property name="url" Value = "JDBC: mysql: / / 127.0.0.1:3306 / test" / > < property name = "username" value = "root" / > < property name = "password" value="123456"/> </dataSource> </environment> <! <environment id="test"> <! <transactionManager type="JDBC"/> <! <dataSource type="POOLED"> <property name="driver" value=" com.mysql.jdbc.driver "/> <property name="url" Value = "JDBC: mysql: / / 127.0.0.1:3306 / test1" / > < property name = "username" value = "root" / > < property name = "password" value="123456"/> </dataSource> </environment> </environments>Copy the code
If we want to change from a development environment to a test environment, we simply need to change the Default attribute in the Environments element
<environments default="test"> <! --> </environments>Copy the code
Mappers elements
The mappers mapper simply tells MyBatis where to find the SQL statement mapping file. Can we use the class resource path to get the mapping file, or URL, etc
<mappers>
<mapper resource="cn/friday/dao/developer/DevUserMapper.xml"/>
<mapper resource="cn/friday/dao/developer/AppInfoMapper.xml"/>
</mappers>
Copy the code
Get the mapping file with the URL
<mappers>
<mapper url="file:///D:/mappers/DevUserMapper.xml"/>
<mapper url="file:///D:/mappers/AppInfoMapper.xml"/>
</mappers>
Copy the code
How to implement MyBatis
I want to show you the structure of my project
The first step is importing the dependency
Mine is a Maven project so I just need to add MyBatis dependencies to the POX. XML configuration file
<? The 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" > The < modelVersion > 4.0.0 < / modelVersion > < groupId > org. Example < / groupId > < artifactId > MyBatis < / artifactId > <version>1.0-SNAPSHOT</version> <dependencies> <groupId>junit</groupId> <artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> < artifactId > mysql connector - Java < / artifactId > < version > 6.0.6 < / version > < / dependency > < the dependency > Mybatis </groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java/</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build> </project>Copy the code
Step 2 Create the MyBatis profile
These are configuration files that we’ve talked about so I don’t want to go into too much detail here
<? The 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" > <configuration> <properties resource="jdbc-config.properties"/> <typeAliases> <package name="com.friday.pojo"/> </typeAliases> <environments default="test"> <environment id="test"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/friday/dao/UserMapper.xml"></mapper> </mappers> </configuration>Copy the code
Properties in jdbc-config.properties
. Driver = com. Mysql. JDBC driver url = JDBC: mysql: / / 127.0.0.1:3306 / test? serverTimezone=UTC username=root password=123456Copy the code
Step 3 Create the interface and mapping file
Interface, plain Java interface
package com.friday.dao; import com.friday.pojo.User; import org.apache.ibatis.annotations.Param; Public interface UserMapper {// @param = String userCode; userPassword = String userCode; public User login(@Param("userCode") String userCode,@Param("userPassword") String pwd); }Copy the code
The mapping file
<? The 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" > < mapper namespace="com.friday.dao.UserMapper"> <select id="login" resultType="User" parameterType="string"> SELECT * FROM smbms_user WHERE userCode=#{userCode} AND userPassword=#{userPassword} </select> </mapper>Copy the code
Properties in mapper files
- The namespace attribute specifies the corresponding interface
- Id Specifies the name of a specific method in the interface property
- ResultType Indicates the type of the returned value
- ResultType Indicates the type of the parameter that is passed in
Step 4 Test
package com.friday.test; import com.friday.dao.UserMapper; import com.friday.pojo.User; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; Public class MyBatisTest {public static void main(String[] args) throws IOException {// Reading the MyBatis configuration file String resource = "mybatis-config.xml"; / / for mybatis config file input stream InputStream is = Resources. The getResourceAsStream (resource); SqlSessionFactory Factory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = factory.openSession(); // Get the corresponding Mapper, let the Mapper find the corresponding SQL through the namespace and method name, send to the database for execution and return the result. User user = sqlSession.getMapper(UserMapper.class).login("zhanghua","userPassword"); If (user! = null) {system.out.println (" login succeeded "); } else {system.out.println (" login failed "); } // Close the sqlSession object sqlsession.close (); }}Copy the code
The last
You can leave a comment below to discuss what you don’t understand. You can also pay attention to my private letter and ask me. I will answer it after I see it. Also welcome everyone to pay attention to my public account: the future is bright, immediately gold nine silver ten job-hunting interview season, sorted out more than 1000 nearly more than 500 pages of PDF document Java interview questions in it, to help you realize your dream BAT! Articles will be updated in it, and sorted data will be placed in it. Thank you for watching, think the article is helpful to you remember to pay attention to me a thumb-up support!