SSM mybatis usage process
Mybatis usage process
1. Import the coordinates of jar or mvan
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.10</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
You also need to add the following in the pom.xml < build > tag to prevent Mapper.xml from being found. If you use the mapper interface, you don't need to add it
<resources> <resource> <directory>src/main/java</directory> <excludes> <exclude>**/*.xml</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> </resources>
2. Create log4j.properties configuration file
Store log information in Mybatis
## set up Logger Output level and output destination (multiple destinations can be specified) ### ### It is generally used during development debugļ¼Use after development error ### ### They correspond to the level of output information. The lower the level, the more detailed the information output is. Use debug At the level of, info The information in can also be output and used info When I was young, debug The corresponding information cannot be displayed ### ### Logger output level: fatal>error>warn>info>debug ### ### The latter two correspond to the lower two. One is printed on the console and the other is printed in the log file log4j.rootLogger=debug,console,logFile ############################################################################################# ### Output log information to the console ### log4j.appender.console=org.apache.log4j.ConsoleAppender ### Print information to System.err Up, red ### log4j.appender.console.Target=System.out ### Specifies the layout type of log output on the console and the type in the specified format ### log4j.appender.console.layout=org.apache.log4j.PatternLayout ### %r: The number of milliseconds it takes to output the log information since the application is started.% x indicates the left alignment when the information is output ### %5p:%p indicates the priority of output log information, i.e. 5 in the middle of DEBUG, INFO, WARN, ERROR and FATAL. The minimum width of control is 5 ### %F: % L% F: file name where the output log message is generated% L: line number in the output code ### %l: The occurrence location of the output log event is equivalent to the combination of% C.%M(%F:%L), including the category name, the thread that occurred, and the number of rows ### %m: Output the message specified in the code and the specific log information generated% n: output a carriage return line feed character, which is "\ r\n" for Windows platform and "\ n" for Unix platform log4j.appender.console.layout.ConversionPattern= -> (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n ############################################################################################# ############################################################################################# ### Output log information to file: log.log Note: if there is a path\The symbol must be written\\ Otherwise it will be escaped ### log4j.appender.logFile=org.apache.log4j.FileAppender ### Specifies the file name of the log output ### log4j.appender.logFile.File=D:/log.log ### Specify conversion mode ### log4j.appender.logFile.layout=org.apache.log4j.PatternLayout ### Specifies the log layout type ### ###log4j.appender.logFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss}%l %F %p %m%n ###log4j.appender.logFile.layout.ConversionPattern= -> (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n log4j.appender.logFile.layout.ConversionPattern= -> (%r ms) - %d{yyyy-MM-dd HH:mm:ss}%x[%5p]%l %m%n #############################################################################################
You don't need to store it manually. Just open log4j in the Mybatis core configuration file
3. Create database parameter configuration file
The key here corresponds to ${driver} in the core configuration file
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false username=root password=root
Note this:? Useunicode = true & characterencoding = utf8 & autoreconnect = true & failoverreadonly = false is particularly important
useUnicode specifies the Unicode encoding format
Whether to use Unicode character set. If the parameter characterEncoding is set to gb2312 or gbk or utf8, the parameter value must be set to true
characterEncoding specifies the encoding type
Does autoReconnect use a reconnect policy for the database connection pool
failOverReadOnly after automatic reconnection is successful, is the connection set to read-only?
4. Create Mybatis core configuration file
<?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> <!--Database configuration file--> <properties resource="database_url.properties" /> <!--open log4j--> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <!--You can map the entity layer directly by name without entering a path--> <typeAliases> <package name="cn.htsa.www.entity"/> </typeAliases> <environments default="development"> <environment id="development"> <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> <!--take UserMapper.xml Add profile to profile--> <mappers> <!--Multiple can be configured--> <package name="cn.htsa.www.dao"/> </mappers> </configuration>
5. Create Mapper.xml configuration file
Then create the UserMapper.xml file under the data access layer dao
This file corresponds to the file in the Mybatis core configuration file
<mappers>
<mapper resource="cn/htsa/www/dao/UserMapper.xml"/>
</mappers>
<?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"> <!--Namespace binding interface class--> <mapper namespace="cn.htsa.www.dao.UserMapper"> <!--Query all data pieces--> <select id="count" resultType="int"> select count(*) from product </select> sql Statement label....... </mapper>
Note: we can also put the mapper.xml file under resources, but the path should be the same as that of mapper.java
For example, if the path of mapper.java is cn.mapper, create cn/mapper under resources (note to use / create instead of.)
Then put mapper.xml below
6. Create Mapper interface [dynamic proxy]
Then create UserMapper.java under the data access layer dao
The interface file corresponds to the interface in UserMapper.xml
<mapper namespace="cn.htsa.www.dao.UserMapper">
The return value parameter of the method name in the interface corresponds to the parameter in the UserMapper.xml file
Interface method name = sql tag id attribute in xml file
Interface return value = sql tag result... Attribute in xml file
Interface parameter = sql tag parameter... Attribute in xml file. If there is no such attribute, it will be calculated according to the parameters in the interface
public interface UserMapper { public int count(); }
7. Create MyBatisUtil tool class
Used to manipulate the database
package cn.htsa.www.dao; 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 MyBatisUtil { private static SqlSessionFactory factory; static { try { String resource = "mybatis-config.xml"; //Load the MyBatis core configuration file into the input stream InputStream is = Resources.getResourceAsStream(resource); //Then create a session factory factory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); } } //Create SqlSession and open transaction public static SqlSession createSqlSession() { return factory.openSession(false); } //sqlSession.commit() should be used in addition, deletion, modification and query// Commit transaction sqlSession.rollback(); Return the transaction, finally call the next method to close the session. //Close SqlSession session public static void closeSqlSession(SqlSession sqlSession){ if(sqlSession!=null){ sqlSession.close(); } } }
8. Test
@Test public void show() { //Access the database by dynamically binding the interface SqlSession sqlSession = MyBatisUtil.createSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int count =mapper.count(); System.out.println(count); //If you do not need to call multiple times, use the method in the mapper interface once int count_ = sqlSession.getMapper(UserMapper.class).count(); System.out.println(count_); //Access the database by path int count1 = sqlSession.selectOne("cn.htsa.www.dao.UserMapper.count"); System.out.println(count1); //Be sure to close the connection after the last use, otherwise the connection pool will be gg full MyBatisUtil.closeSqlSession(sqlSession);//Close connection }
Through the above sections, you can use the Mybatis framework
If the Mapper.xml file is not found, the solution
1. Check whether mybatis-config.xml path is correct
It does not need to be in the same directory as the interface, but it needs to be specified one by one (it must be ensured that the name of the interface and the mapping configuration file are the same)
<mappers> <mapper resource="cn/htsa/www/dao/UserMapper.xml"/> </mappers>
(ensure that the interface and mapping configuration file names are the same and in the same level directory)
<mappers> <package name="com.htsa.dao"/> </mappers>
2. Check whether the namespace in Mapper.xml points to Mapper.java interface
<mapper namespace="cn.htsa.www.dao.UserMapper"> </mapper>
Generally, if the first two items are OK, it is definitely the third item
3. Add in the build of pom.xml, otherwise Mapper.xml cannot be found
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
-
mapper.xml cannot be found in resources in IDEA
The reason is that when you create a package, you input it at one time. For example, the package generated by cn.baidu.mapper is not the package Baidu in CN, and then Baidu contains mapper, but cn.baidu.mapper is a package. If you don't believe it, you can go and have a look locally
The correct way to create packages under resources is to use cn/baidu/mapper or create directories level by level
In this way, the mapper interface and mapper.xml mapping file can be in the same directory after compilation
If it doesn't work, restart the IDEA and try. Anyway, sometimes it's an evil door. I've experienced nothing, but I can't find it, and then restart the IDEA
On the Internet, it is also said to add a space metaphysics to the file
mapper.xml in IDEA cannot be found in resources
The reason is that when you create a package, you input it at one time. For example, the package generated by cn.baidu.mapper is not the package Baidu in CN, and then Baidu contains mapper, but cn.baidu.mapper is a package. If you don't believe it, you can go and have a look locally
The correct way to create packages under resources is to use cn/baidu/mapper or create directories level by level
In this way, the mapper interface and mapper.xml mapping file can be in the same directory after compilation
If it doesn't work, restart the IDEA and try. Anyway, sometimes it's an evil door. I've experienced nothing, but I can't find it, and then restart the IDEA
On the Internet, it is also said to add a space metaphysics to the file
Like - collect - pay attention Easy to review and receive the latest content in the future If you have other questions to discuss in the comment area - or send me a private letter - you will reply as soon as you receive them Thank you for your cooperation. I hope my efforts will be helpful to you^_^