New Mybatis-xml File Deployment and Simple Application

Initial Mybatis-xml file deployment and simple application (Dao mode)

Tools used

mybatis-3.2.7.jar
mysql-connector-java-8.0.16.jar
mybatis
myeclipse
mysql5.5.15
navicat
Use the tool to search for it by oneself! ____________

1. Open Navicat to create a table for testing

  • mysql creates database
CREATE DATABASE mybatisTest
  • mysql creates data tables
CREATE TABLE test(
   testID INT UNSIGNED AUTO_INCREMENT, //Primary key, self-increasing
   testName VARCHAR(100) NOT NULL,     //Not empty
   testPassword VARCHAR(100) NOT NULL,
   testAge INT NOT NULL,
   PRIMARY KEY (testID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
  • Adding data to the test table
INSERT into test (testName,testPassword,testAge) values("Xiao Ming","123",18)
INSERT into test (testName,testPassword,testAge) values("Xiaohong","456",17)
INSERT into test (testName,testPassword,testAge) values("Xiaogang","789",20)
INSERT into test (testName,testPassword,testAge) values("Little thunder","542",19)
INSERT into test (testName,testPassword,testAge) values("Xiaofang","873",18)
INSERT into test (testName,testPassword,testAge) values("Xiaohua","452",19)

Data Table Display

2. Open MyEclipse to create a new project

3. Basic configuration

  • Create a lib folder to store jar packages and associate them with the project
  • Create a package storage entity class: cn.edu.student.entity
package cn.edu.student.entity;

public class TestEntity {

	private Integer testID;
	private String testName;
	private String testPassword;
	private Integer testAge;

Note: The encapsulated entity class attribute names must correspond to the tables in the database one by one, otherwise mybatis can not recognize the error!

  • Create a package to store the test class: cn.edu.student.test
  • Create a package to store the dao class: cn.edu.student.dao
package cn.edu.student.dao;

import java.util.ArrayList;

import cn.edu.student.entity.TestEntity;

public interface TestDao {

	/**
	 * Adding operations
	 * @param testEntity Increased membership
	 * @return Boolean type
	 */
	abstract public boolean addTest(TestEntity testEntity);
	
	/**
	 * Delete operations based on testid
	 * @param testID target ID
	 * @return Boolean type
	 */
	abstract public boolean deleteTestByID(int testID);
	
	/**
	 * Modify testPassword according to testName
	 * @param testName Target name
	 * @param testPassword Change Password
	 * @return Boolean type
	 */
	abstract public boolean updateTestByName(String testName,String testPassword);
	
	/**
	 * Full check operation
	 * @return Collection of members
	 */
	abstract public ArrayList<TestEntity> getAll();
}

  • Create a package to store the dbutil class: cn.edu.student.dbutil
package cn.edu.student.dbutil;

import java.io.InputStream;
import java.util.ArrayList;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.edu.student.dao.TestDao;
import cn.edu.student.entity.TestEntity;
import cn.edu.student.test.TestBatis;

public class TestDBUtil {

	/**
	 * Get a conversation
	 * @return Create a good session
	 */
	public SqlSession creatSession(){
		String path = "SqlMapConfig.xml"; //The relative path of SqlMapConfig.xml, because my SqlMapConfig.xml file is in the root directory, so I only write the file name.
		InputStream inputStream = TestBatis.class.getClassLoader().getResourceAsStream(path); //InputStream byte input stream to get the loader of the TestBatis class to load the SqlMapConfig.xml Mapping File
		SqlSessionFactory sqlSessionFactory =new SqlSessionFactoryBuilder().build(inputStream); //Create a session factory
		SqlSession sqlSession = sqlSessionFactory.openSession(); //Get a conversation
		return sqlSession;
	}
	
	/**
	 * Session closure
	 * @param sqlSession
	 */
	public void closeAll(SqlSession sqlSession){
		sqlSession.commit(); //Session submission
		sqlSession.close();  //Session closure
	}
	
	/**
	 * addtest corresponding to testdao class
	 * @param testEntity
	 * @return
	 */
    public boolean addTest(TestEntity testEntity){
    	SqlSession sqlSession = creatSession();
    	TestDao testDao = (TestDao) sqlSession.getMapper(TestDao.class);
    	if(testDao.addTest(testEntity)){
			closeAll(sqlSession);
			return true;
		}
		else {
			closeAll(sqlSession);
			return false;
		}
    }
	
    /**
     * deleteTestByID corresponding to testdao class
     * @param testID
     * @return
     */
	public boolean deleteTestByID(int testID){
		SqlSession sqlSession = creatSession();
    	TestDao testDao = (TestDao) sqlSession.getMapper(TestDao.class);
    	if(testDao.deleteTestByID(testID)){
			closeAll(sqlSession);
			return true;
		}
		else {
			closeAll(sqlSession);
			return false;
		}
	}
	
	/**
	 * updateTestByName corresponding to testdao class
	 * @param testName
	 * @param testPassword
	 * @return
	 */
	public boolean updateTestByName(String testName,String testPasssword){
		SqlSession sqlSession = creatSession();
    	TestDao testDao = (TestDao) sqlSession.getMapper(TestDao.class);
    	if(testDao.updateTestByName(testName,testPasssword)){
			closeAll(sqlSession);
			return true;
		}
		else {
			closeAll(sqlSession);
			return false;
		}
	}
	
	/**
	 * getAll corresponding to testdao class
	 * @return
	 */
	public ArrayList<TestEntity> getAll(){
		SqlSession sqlSession = creatSession();
    	TestDao testDao = (TestDao) sqlSession.getMapper(TestDao.class);
    	return testDao.getAll();
	}
}
	
	/**
	 * getAll corresponding to testdao class
	 * @return
	 */
	public ArrayList<TestEntity> getAll(){
		SqlSession sqlSession = creatSession();
    	TestDao testDao = (TestDao) sqlSession.getMapper(TestDao.class);
    	return testDao.getAll();
	}
}

Note: When doing the operation of adding, deleting and modifying, we must remember to submit the session, that is, commit operation. Find can not be used!

  • Create a package to store the daoimpl class: cn.edu.student.daoimpl
package cn.edu.student.daoimpl;

import java.util.ArrayList;

import cn.edu.student.dao.TestDao;
import cn.edu.student.dbutil.TestDBUtil;
import cn.edu.student.entity.TestEntity;

public class TestDaoImpl implements TestDao {

	private TestDBUtil testDBUtil = new TestDBUtil();
	
	@Override
	public boolean addTest(TestEntity testEntity) {
		// TODO Auto-generated method stub
		return testDBUtil.addTest(testEntity);
	}
	
	@Override
	public boolean deleteTestByID(int testID) {
		// TODO Auto-generated method stub
		return testDBUtil.deleteTestByID(testID);
	}
	
@Override
	public boolean updateTestByName(String testName,String testPassword) {
		// TODO Auto-generated method stub
		return testDBUtil.updateTestByName(testName,testPassword);
	}
	
	@Override
	public ArrayList<TestEntity> getAll() {
		// TODO Auto-generated method stub
		return testDBUtil.getAll();
	}
}

4. SqlMapConfig.xml file configuration

Place the SqlMapConfig.xml file in the root directory of the working path

The following are the related configurations (I'm just briefly configuring here, but there are many related configurations, such as the maximum number of connections and so on, which I omitted).

<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- and spring After integration environments Configuration will be abolished-->
	<environments default="development">
		<environment id="development">
		<!-- Use jdbc transaction management-->
			<transactionManager type="JDBC" />
		
			<dataSource type="POOLED">  
			    <!-- mysql Of jdbc8.0 All of the above versions of driver loads are used“ com.mysql.cj.jdbc.Driver" Be careful -->
		    	<property name="driver" value="com.mysql.cj.jdbc.Driver" />
		    	<!-- fill in url Be careful not to look like in java It's the same as in the file, because the variables here must be useful.;Separation, so change it -->
				<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatistest?useUnicode=true&amp;serverTimezone=GMT&amp;useSSL=false" />
				<property name="username" value="root" />
				<property name="password" value="6134" />
			</dataSource>
		</environment>
	</environments>
	
	<!-- Load mapper.xml -->
	<mappers>
	    <!-- There are file paths and class paths in the writing of paths. Pay attention to the use of file paths./Separation, while classpath use.Number separation, this point of attention to distinguish -->
		<mapper resource="cn/edu/student/dao/TestDaoMapper.xml" />
	</mappers>
	
</configuration>

5. Mapper.xml file configuration

Put the TestDaoMapper.xml file in the directory of the dao package

<?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 Namespaces, in order to sql Statements are isolated to facilitate management. mapper Development dao Way, use namespace It has a special function. Pay attention to what must be written corresponds to it. dao Path -->
<!-- This place is the class path. -->
<mapper namespace="cn.edu.student.dao.TestDao">
<!-- stay mapper.xml There are many configurations in the file sql Statement, execute each sql When a statement is executed, it is encapsulated as MappedStatement object
mapper.xml with statement Unit management sql Sentence
 -->
 
 <!-- addTest -->
 <!-- Be careful id Must correspond to dao The method in the code does not support duplication id -->
 <!-- parameterType Represents the type of entry -->
 <!-- write sql Statement recommendation now Navicat Running once to prevent mistakes -->
<insert id="addTest" parameterType="cn.edu.student.entity.TestEntity">
INSERT into test(testName,testPassword,testAge) values(#{testName},#{testPassword},#{testAge})
</insert>

<!-- deleteTestByID-->
<!-- The name of a single parameter can be changed into any name without any tangle. -->
<delete id="deleteTestByID" parameterType="java.lang.Integer">
delete from test where testID=#{testID}
</delete>

<!-- updateTestByName-->
<!-- Multiparameter parameters can be entered without writing parameter types, and the index can be represented by numbers, but only by and. dao The method parameters in the -->
<update id="updateTestByName">
UPDATE test set testPassword = #{1} WHERE testName = #{0}
</update>

<!-- getAll -->
<!-- resultType Is the return type -->
<select id="getAll" resultType="cn.edu.student.entity.TestEntity">
Select * from test
</select>

</mapper>


6. Writing test classes

package cn.edu.student.test;

import cn.edu.student.daoimpl.TestDaoImpl;
import cn.edu.student.entity.TestEntity;

public class TestBatis {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		TestDaoImpl testDaoImpl = new TestDaoImpl();
		System.out.println("**********addTest************");
		TestEntity testEntity = new TestEntity();
		testEntity.setTestName("Xiaofei");
		testEntity.setTestPassword("546");
		testEntity.setTestAge(20);
		System.out.println(testDaoImpl.addTest(testEntity));
		System.out.println("**********updateTestByName************");
		System.out.println(testDaoImpl.updateTestByName("Xiaofei", "412"));
		System.out.println("**********deleteTestByID************");
		System.out.println(testDaoImpl.deleteTestByID(8));
		System.out.println("**********getAll************");
		testDaoImpl.getAll().forEach(System.out::println);
	}

}

7. Be careful and sum up

Screenshots of experimental results

Initial framework learns dao mode, realizes that sql statements are separated from java files, and prevents them from becoming class files after java compilation. It is difficult to modify sql statements because xml files are not compiled, so modifying sql statements is very simple. dao mode is also a commonly used development mode. After that, learning mybatis framework will be more in-depth.

Tags: xml Mybatis Java Session

Posted on Sun, 04 Aug 2019 21:23:02 -0700 by ckjian