Environment Construction of Mybatis

Step 1: Import two jar packages, mybatis.jar and mysql-connector-java-bin.jar

Step 2: Create a mybatis-config configuration file in which connection settings with data are completed, as shown in Figure 1:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 1,dtd Configuration files must be written in accordance with their requirements. -->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 2,Configuration environment, develop Is the development environment -->
	<environments default="develop">
		<!-- 3,Configure specific environment and development environment -->
		<environment id="develop">
			<!-- 4,Configure transaction management, specified as JDBC type -->
			<transactionManager type="JDBC" />
			<!-- 5,Set up the data source with the type of ____________ POOLED Data pool -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost:3306/db_mybatis" />
				<property name="username" value="root" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<!-- 6,Registration mapping file -->
	<mappers>
		<mapper resource="com/mybatis/pojo/userMapper.xml" />
	</mappers>
</configuration>

Step 3: Create the corresponding entity class according to the table structure, as shown in the figure:

Created entity classes

package com.mybatis.pojo;

public class User {

	private int id;
	private String name;
	private String password;
	private String nickname;
	private String email;

	public User() {
		super();
	}

	public User(String name, String password, String nickname, String email) {
		super();
		this.name = name;
		this.password = password;
		this.nickname = nickname;
		this.email = email;
	}

	public User(int id, String name, String password, String nickname, String email) {
		super();
		this.id = id;
		this.name = name;
		this.password = password;
		this.nickname = nickname;
		this.email = email;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password + ", nickname=" + nickname + ", email="
				+ email + "]";
	}

}

Step 4: Create a mapper file to complete the mapping of the entity class. The file is also an xml file, as shown in the figure:

<?xml version="1.0" encoding="UTF-8"?>
<!-- dtd Configuration files must be written in accordance with their requirements. -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- Set up a namespace to use the full path of the entity -->
<mapper namespace="com.mybatis.pojo.User">
	
	<!-- Add information -->
	<insert id="add" parameterType="com.mybatis.pojo.User">
		insert into t_user(name,password,nickname,email)
		values(#{name},#{password},#{nickname},#{email})
	</insert>
	
	<!-- Delete information -->
	<delete id="del" parameterType="int">
		delete from t_user where id = #{id}
	</delete>
	
	<!-- Modify information -->
	<update id="update" parameterType="com.mybatis.pojo.User">
		update t_user 
		set name = #{name}, password = #{password}, nickname = #{nickname}, email = #{email}
		where id = #{id}
	</update>
	
	<!-- Query for all information -->
	<select id="queryall" resultType="com.mybatis.pojo.User">
		select * from t_user
	</select>

	<!-- according to id Query information -->
	<select id="load" parameterType="int" resultType="com.mybatis.pojo.User">
		select * from t_user where id = #{id}
	</select>
</mapper>

Step 5: Create SqlSession in the test class and complete the operation of the database through SqlSession

package com.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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.mybatis.pojo.User;

public class MyBatisTest {

	@SuppressWarnings({ "null", "unused" })
	public static void main(String[] args) {
		SqlSession session = null;
		int i = 0;
		try {
			// 1. Load the configuration file of mybatis (also load the associated mapping file)
			InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
			// 2. Building SqlSession Factory
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
			// 3. Create sqlSession that can execute mapping files
			session = factory.openSession();
			// 4. Executing sql statements
			
			// insert adds data
//			User addUser = new User("Lisi", "qqq", "Xiaoli", "lisi@qq.com");
//			i = session.insert("com.mybatis.pojo.User.add", addUser);
//			session.commit(); // transaction commit
//			session.close(); //close
//			if(i != 0) {
//				System.out.println("Add Successfully! "";
//			}
			
			// del deletes data according to id
//			i = session.delete("com.mybatis.pojo.User.del", 2);
//			session.commit(); // transaction commit
//			session.close(); //close
//			if(i != 0) {
//				System.out.println("Delete successfully! "";
//			}
			
			// update modifies data
//			User updateUser = new User(2, "wangwu", "wangwu", "wang", "wang@163.com");
//			i = session.update("com.mybatis.pojo.User.update", updateUser);
//			session.commit(); // transaction commit
//			session.close(); //close
//			if(i != 0) {
//				System.out.println("Successful modification! "";
//			}
			
			// select queries based on id
//			User loadUser = session.selectOne("com.mybatis.pojo.User.load", 1);
//			System.out.println(loadUser);
			
			// select queries all data
			List<User> users = session.selectList("com.mybatis.pojo.User.queryall");
			for(User user : users) {
				System.out.println(user);
			}
		} catch (IOException e) {
			session.rollback(); // Transaction rollback
			e.printStackTrace();
		}
		
	}
	
}

 

 

 

Tags: Mybatis Session xml Java

Posted on Mon, 07 Oct 2019 12:07:28 -0400 by Scottya