Introduction to MyBatis
MyBatis's predecessor was iBatis, which was originally an open source project of apache. In 2010, this project was moved from apache software foundation to Google code and was renamed MyBatis.
MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plan Old Java Objects, ordinary Java objects) into records in the database.
The following steps are introduced to the construction of mybatis environment.
1) Introduce the mybatis-3.4.1.jar package under the project, and then introduce the database (mysql,mssql..) package.
2) Create a new configuration file conf.xml under src
<?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><!-- Introducing external configuration files--> <properties resource="jdbc.properties" /> <!-- Configure mybatis operating environment--> <environments default="development"> <environment id="development"> <!-- type="JDBC" Represents the use of JDBC's commit and rollback to manage transactions --> <transactionManager type="JDBC" /> <!-- mybatis provides three data source types, namely: POOLED,UNPOOLED,JNDI --> <!-- POOLED indicates support for JDBC data source connection pool--> <!-- UNPOOLED indicates not to support for data source connection pool--> <!-- JNDI indicates support for external data source connection pool--> <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="userMapper.xml"/> </mappers> </configuration>Here, the database storage information is stored through external configuration files, so a jdbc.properties database storage information is added.
driver=com.microsoft.sqlserver.jdbc.SQLServerDriverurl=jdbc:sqlserver://127.0.0.1;databaseName=testusername=sapassword=123456
3) Create a mapping file userMapper.xml
<?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="hw.com.ser.IUser"> <!-- Query all users--> <select id="queryUsers" resultType="hw.com.pojo.User"> select * from MS_User </select> <selectid="queryUserById" resultType="hw.com.pojo.User" parameterType="int"> Select * From Ms_User Where id=#{id} </select> </mapper>(It should be noted here that the namespace attribute is, because this instance is mapped through interfaces, so the namespace attribute should be written as the path of the interface) Attached figure:
4) Create a mapping interface class
package hw.com.ser;import java.util.List;import hw.com.pojo.User;public interface IUser { public List<User> queryUsers(); public User queryUserById(int id);}5) Create a SqlSessionFactory
package hw.com.util;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.Reader;import java.util.Properties;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionFactoryUtil { private static SqlSessionFactory sqlSessionFactory = null; private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class; private SqlSessionFactoryUtil() { } public static SqlSessionFactory initSqlSessionFactory() { String resource = "conf.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } synchronized (CLASS_LOCK) { if (sqlSessionFactory == null) { sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } } return sqlSessionFactory; } public static SqlSession openSqlSession(){ if(sqlSessionFactory==null){ initSqlSessionFactory(); } return sqlSessionFactory.openSession(); }}6) Create a pojo
package hw.com.pojo;import java.util.Date;public class User { private String Id; private String UserName; private String UserPwd; private int DeptmentId; private String UserTrueName; private String Email; private int LearnCenterId; private Date CreateDate; private Date LastModifyDate; private int UserStatus; public User() { super(); // TODO Auto-generated constructor stub } public String getId() { return Id; } public void setId(String id) { Id = id; } public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public String getUserPwd() { return UserPwd; } public void setUserPwd(String userPwd) { UserPwd = userPwd; } public int getDeptmentId() { return DeptmentId; } public void setDeptmentId(int dependmentId) { DeptmentId = dependmentId; } public String getUserTrueName() { return UserTrueName; } public void setUserTrueName(String userTrueName) { UserTrueName = userTrueName; } public String getEmail() { return Email; } public void setEmail(String email) { Email = email; } public int getLearnCenterId() { return LearnCenterId; } public void setLearnCenterId(int learnCenterId) { LearnCenterId = learnCenterId; } public Date getCreateDate() { return CreateDate; } public void setCreateDate(Date createDate) { CreateDate = createDate; } public Date getLastModifyDate() { return LastModifyDate; } public void setLastModifyDate(Date lastModifyDate) { LastModifyDate = lastModifyDate; } public int getUserStatus() { return UserStatus; } public void setUserStatus(int userStatus) { UserStatus = userStatus; } @Override public String toString() { return "User [Id=" + Id + ", UserName=" + UserName + ", UserPwd=" + UserPwd + ", DeptmentId=" + DeptmentId + ", UserTrueName=" + UserTrueName + ", Email=" + Email + ", LearnCenterId=" + LearnCenterId + ", CreateDate=" + CreateDate + ", LastModifyDate=" + LastModifyDate + ", UserStatus=" + UserStatus + "]"; }}7) Do the test under the main method
package hw.com.Day1.main;import java.util.List;import org.apache.ibatis.session.SqlSession;import hw.com.pojo.User;import hw.com.ser.IUser;import hw.com.util.SqlSessionFactoryUtil;public class UserTest { public static void main(String[] args) { SqlSession sqlSession=null; try { sqlSession=SqlSessionFactoryUtil.openSqlSession(); IUser iUser=sqlSession.getMapper(IUser.class); List<User> users=iUser.queryUsers(); if(users.size()>0){ for (User user : users) { System.out.println(user.toString()); } } } catch (Exception e) { e.printStackTrace(); } }}