1. Create a Web Project with Maven
In order to complete the integration of Spring 4.x and MyBatis3.X smoothly, first review the creation of a web project in the Maven environment and use MyBatis3.X. The first and second content is mostly about reviewing the past content.
1.2. Click "File"->"New"->"Other"->Enter "Maven" and create a new "Maven Project", as shown in the figure below:
1.2. Please check "Create a simple project" to create a simple project without using templates. You can also use the template and select WebApp, but you should not check it here. As shown in the figure below:
1.3. Fill in the package name and project name, and select the packaging type as: war, as shown in the figure below:
1.4. After the project is created, you may find an error. Select the project, right-click "Properties"->"Layer Project Facets"->"Java" and modify the version number to 1.7, and the default is 1.5; click "Ok" to save and close it. As shown in the figure below:
1.5. Repeat the previous step, back-tick the Dynamic Web Module, and temporarily turn the project into a non-Web project. Click "Ok" to save and close it.
1.6. Repeat the previous step, then go to the level attributes, check "Dynamic Web Module" and select Version to 3.0. Click the hyperlink "Further Configuration available..." in the lower left corner.
1.7. Check "Generate web.xml deployment descriptor" to generate the web.xml deployment description file. Click "Ok" to save and close it.
1.8. Copy the two folders "META-INF" and "WEB-INF" in the generated WebContent directory to the src/main/webapp directory.
1.9. Delete the WebContent directory.
1.10. After deleting, you will find that the project's pom.xml file errors are reported because the web.xml file in the specified location cannot be found. Enter the project properties, select the "Deployment Assembly" project deployment item, and delete the "src/test/java", "src/test/resources" and "WebContent" directories, because these three items do not need to be deployed.
1.11. Click "Add" and select "Folder folder" to specify the web content root folder for the final deployment result of the project.
1.12. Select the src/main/webapp directory as the target directory, click "Finish" to save and close.
1.13. If the project still reports an error at this time, the error will disappear after modifying the pom.xml file and saving it.
1.14. Create a new index.jsp file in the src/main/webapp directory for testing.
1.15. After the new creation is completed, an error is found because there is no JavaEE Server Runtime. Right-click the property on the project and select the "Java Build Path" item, and click "Add Library..." to add a reference.
1.16. Select the Server Runtime item, click "Next Next", and then select "Apache Tomcat v7.0". You may have to choose according to your own operating environment. If you don't have a Server, you should first integrate Tomcat.
1.17. Write the test content in the index.jsp file.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Hello World!</title></head><body>Hello World!<p><%=new java.util.Date().toLocaleString() %></p></body></html>
1.18. Right-click on the project to run the project and select "Run as"-> "Run on Server" and run the project. The running results are as follows.
2. Use MyBatis to complete MySQL database access
2.1. Add dependencies
To complete using MyBatis to access the MySQL database, you need to add some dependency packages, including MyBatis3, connection driver, JUnit, Log4j2, etc. You can search in the shared resource library. The first website address is: http://mvnrepository.com/. Here, search for connection drivers is an example. The results after searching are many versions of 5.xx and 6.xx, but it is not recommended to use version 6.xx because MyBatis3 does not support it.
We select 5.1.38 in version 5.0 and copy Maven's dependencies to the dependencies node of pom.xml in the project
Of course, you can also go to another website: http://search.maven.org/. Here, you can search for log4j as an example as follows:
If you have some dependencies, you can also go directly to the official website to search, such as MyBatis3:
The project's pom.xml file is as follows:
<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"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhangguo</groupId> <artifactId>Spring061</artifactId> <version>0.0.1</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies></project>
Quote results:
If the network speed is unstable, the download package is likely to fail. You can try to force the project to be re-downloaded; you can use the download tool to copy the jar package to the local resource library after downloading.
2.2. Prepare data
Open the MySQL database and create a table. Here we take the booktypes table as an example.
The sql script is as follows:
/*Navicat MySQL Data TransferSource Server : localhostSource Server Version : 50536Source Host : localhost:3306Source Database : db2Target Server Type : MYSQLTarget Server Version : 50536File Encoding : 65001Date: 2016-07-04 10:49:56*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for `booktypes`-- ----------------------------DROP TABLE IF EXISTS `booktypes`;CREATE TABLE `booktypes` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '类型编号', `typeName` varchar(100) NOT NULL COMMENT '类型名称', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=94 DEFAULT CHARSET=utf8;-- ------------------------------ Records of booktypes- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- `booktypes` VALUES ('6', 'test type');INSERT INTO `booktypes` VALUES ('7', '91');INSERT INTO `booktypes` VALUES ('8', '92');INSERT INTO `booktypes` VALUES ('9', '93');INSERT INTO `booktypes` VALUES ('91', 'architectural design');INSERT INTO `booktypes` VALUES ('92', 'industrial design');INSERT INTO `booktypes` VALUES ('93', 'Made in Ship');2.3. Create a java bean
Add the class BookType type under package com.zhangguo.Spring61.entities.
package com.zhangguo.Spring61.entities;/** * Book type* */public class BookType { /** * Number*/ private int id; /** * Type name*/ private String typeName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; }2.4. Create a mapping file for instances and tables
This is done in the form of interface + XML. The BookType data access interface is as follows:
package com.zhangguo.Spring61.mapping;import java.util.List;import com.zhangguo.Spring61.entities.BookType;/** * Book type data access interface* */public interface BookTypeDAO { /* * Get all book types*/ public List<BookType> getAllBookTypes();}The BookTypeMapper.xml file is as follows:
<?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"><!--The namespace should be the package name + class name of the corresponding interface--><mapper namespace="com.zhangguo.Spring61.mapping.BookTypeDAO"> <!--id should be a method in the interface. If there is no alias, the full name should be used--> <select id="getAllBookTypes" resultType="BookType"> select id,typeName from booktypes </select></mapper>
2.5. Create MyBatisCfg.xml file
The MyBatisCfg.xml file is used to configure the running environment of MyBatis, and the content is as follows:
<?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> <!-- Specify the location of database connection information --> <properties resource="db.properties"></properties> <!-- Type alias, all classes under com.zhangguo.Spring61.entities --> <typeAliases> <package name="com.zhangguo.Spring61.entities"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <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> <!--Introduce the mapping file--> <mapper resource="com/zhangguo/Spring61/mapping/BookTypeMapper.xml" /> </mappers></configuration>Because the configuration relies on the db.properties file, this file is used to specify the connection information of the database, and the content is as follows:
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/db2username=rootpassword=root
2.6. Implement data access function
In order to more conveniently reuse MyBatis to achieve data access, there is no need to frequently create SQLSessionFactory and SQLSession objects, encapsulate a MyBatisUtil tool class as follows:
package com.zhangguo.Spring61.dao;import java.io.InputStream;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public abstract class MyBatisUtil { //GC ignores static private static SqlSessionFactory factory=null; public static SqlSessionFactory getSqlSessionFactory(){ if(factory==null){ // Get the environment configuration file stream InputStream config = MyBatisUtil.class.getClassLoader().getResourceAsStream("MyBatisCfg.xml"); // Create a sql session factory factory = new SqlSessionFactoryBuilder().build(config); } return factory; } // Get the session public static SqlSession getSession(){ return getSqlSessionFactory().openSession(true); } /** * Get the sql session* @param isAutoCommit Whether to submit automatically, if false, sqlSession.commit();rollback(); * @return sql session*/ public static SqlSession getSession(boolean isAutoCommit){ return getSqlSessionFactory().openSession(isAutoCommit); }}Create a class BookTypeDAO class to implement the interface BookTypeDAO. Here we need to implement the data access function through MyBatis, and the content is as follows:
package com.zhangguo.Spring61.dao;import java.util.List;import org.apache.ibatis.session.SqlSession;import com.zhangguo.Spring61.entities.BookType;import com.zhangguo.Spring61.mapping.BookTypeDAO;/** * Implement book type data access* */public class BookTypeDAOImpl implements BookTypeDAO { @Override public List<BookType> getAllBookTypes() { //Get session object SqlSession session=MyBatisUtil.getSession(); try { //Implement the interface BookTypeDAO through MyBatis, return the instance BookTypeDAO bookTypeDAO=session.getMapper(BookTypeDAO.class); return bookTypeDAO.getAllBookTypes(); } finally { session.close(); } }}3. Use Spring 4.X to integrate MyBatis3.X
The above is a detailed explanation of the Spring integration MyBatis (Maven+MySQL) graphic tutorial introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!