Mybatis development environment, select: Eclipse, MySQL 5.5, JDK 1.8, mybatis 3.2.3.jar package. These software tools can be downloaded from their official websites.
The whole process is summarized as follows.
In this tutorial, build java Engineering, but generally is the development of web projects, this series of tutorials is finally the web, but here in order to facilitate learning, this tutorial is built before the java project.
Create two user-defined libraries (User Libary): mysql-connector and mybatis by using mybatis-3.2.3.jar and mysql-connector-java-5.1.25-bin.jar.
-
Establish mysql Test the database and user tables. Note that the database uses utf-8 encoding. In order to solve the unnecessary Chinese scrambling problem.
I. Creating Java Engineering
First, create a java project named Helloword. Select File - > New - > Java Project, as shown in the following figure:
This creates a Java project, and we move on to the next step. Next, we add two libraries to the mybatis-start project: mysql-connector and mybatis. Right-click on the "mybatis-start" project and select "Build Path" - > "Add Libaries..." from the pop-up menu. As shown in the following figure:
Select "User Library" and click "Next>" to create two class libraries: mysql-connector and mybatis, as follows:
Click on "User Libararies..." Go ahead and create a new class library, as shown in the following figure:
And click Add Extral JARs to add the corresponding jar package to one of the user's class libraries and create another in the same way:
2. Creating databases and User tables
To create the required database and tables, the database to be created is: yiibai, and create a table in the yiibai database: user
Next, we create a table: user and insert a record information, which is structured as follows:
//Create a database
CREATE DATABASE yiibai;
//Create table
USE yiibai;
CREATE TABLE `user` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(64) NOT NULL DEFAULT '',
`dept` VARCHAR(254) NOT NULL DEFAULT '',
`website` VARCHAR(254) DEFAULT '',
`phone` VARCHAR(16) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
//insert data
INSERT INTO `user` VALUES ('1', 'yiibai', 'Tech', 'http://www.yiibai.com', '13800009988');
Create Mybatis configuration file
So far, the preparatory work has been completed. Let's begin to really configure the mybatis-start project. Set up the mybatis configuration file: Configure.xml, and create the file in the src/config directory 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>
<typeAliases>
<typeAlias alias="User" type="com.yiibai.mybatis.models.User" />
</typeAliases>
<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/yiibai" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- Mapping file -->
<mappers>
<!-- // power by http://www.yiibai.com -->
<mapper resource="com/yiibai/mybatis/models/User.xml" />
</mappers>
</configuration>
4. Creating Entity Classes and Mapping Files
First create a package: com.yiibai.mybatis.models, and then create the User.java class corresponding to the database table and its mapping file: User.xml, as shown in the following figure:
package com.yiibai.mybatis.models;
public class User {
private int id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String dept;
private String phone;
private String website;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
}
At the same time, the mapping file User.xml corresponding to this User class is established, as shown in the following code:
<?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.yiibai.mybatis.models.UserMapper">
<select id="GetUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
Following is an explanation of these configuration files:
1. Configuration file
Configure.xml is used by mybatis to build sessionFactory, which mainly contains database connection related content, as well as the alias corresponding to java class, such as: <type Alias alias="User" type="com.yiibai.mybatis.models.User"/> This alias is very important in the mapping of specific classes, such as: resultType in User.xml corresponds to this alias="User" type="com.yiibai.mybatis.models.User"/>. To maintain consistency, resultType here also has a separate way of defining it, which we'll discuss in more detail later.
2. The <mapper resource="com/yiibai/mybatis/models/User.xml"/> in Configure.xml is the XML configuration file containing the classes to be mapped.
3. In the User.xml file, it mainly defines various SQL statements, and the parameters of these statements, as well as the types to be returned, and so on.
5. Running program test results
Create a class called HelloWord under the src source directory to run the test configuration environment successfully. The specific code is as follows:
import java.io.Reader;
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 com.yiibai.mybatis.models.User;
public class HelloWord {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("config/Configure.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SqlSession session = sqlSessionFactory.openSession();
try {
User user = (User) session.selectOne(
"com.yiibai.mybatis.models.UserMapper.GetUserByID", 1);
if(user!=null){
String userInfo = "Name:"+user.getName()+", Departments:"+user.getDept()+", Home page:"+user.getWebsite();
System.out.println(userInfo);
}
} finally {
session.close();
}
}
}
Now run this program, not get the query results? The correct output should be as follows:
In-depth understanding: