Is MyBatis persistence layer frame (SQL mapping framework) - operate the database

Is MyBatis persistence layer frame (SQL mapping framework) - operate the database

1, built environment

     1) Create a java project;

     2) create a library dao interface testing, javaBean test table, and a package of data, and the operation of the database

           

       Create a table: create your own tools

               Create javaBean: (encapsulated data table) the Employee

Employee.java

package com.atguigu.bean;

public class Employee {
	
	private Integer id;
	private String empName;
	private String email;
	private Integer gender;

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Employee [id=" + id + ", empName=" + empName + ", email="
				+ email + ", gender=" + gender + "]";
	}
}

               Create a Dao interface for operation of the database;



 3, with MyBatis operate the database?

     1, the leader packet

    

       It recommended import log package; in critical link mybatis will have to print the log;

       log4j (logging framework); a path-dependent class log4j.xml profile;


 2, write configuration (two, global configuration file (guidance mybatis run) , implementation file interface dao (dao description of each method how to work)

               1), the first profile; (called mybatis global configuration file, mybatis guidance on how to run properly, such as connecting to a database which)

               2), the second profile :( write every method how to send sql statements to the database, how to perform the equivalent of interface implementation class ....)

                             1), the mapper of the namespace attribute to the full name of the class interface

                             2), configuration details

   Two files:

     1), a global profile: mybatis-config.xml ; some global guidance mybatis correct operation of the set;

     2), the SQL mapping file: EmployeeDao.xml ; is equivalent to a description of the realization of the interface Dao



detail:

     1), acquired a proxy object interface; mybatis automatically created;

     2), a SqlSessionFactory and the SqlSession ;

          SqlSessionFactory SqlSession create objects, Factory only new one on the line

         SqlSession: the equivalent of a database connection and interact, and a session database , you should create a new sqlSession;




Employee.java

package com.atguigu.bean;

public class Employee {
	
	private Integer id;
	private String empName;
	private String email;
	private Integer gender;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}

	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}

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

	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", empName=" + empName + ", email="
				+ email + ", gender=" + gender + "]";
	}
}

EmployeeDao.java

package com.atguigu.dao;

import com.atguigu.bean.Employee;

public interface EmployeeDao {
    //按照员工id查询员工
    public Employee getEmpById(Integer id);
}

mybatis-config.xml

<?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>
	
  <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://localhost:3306/mybatis_0325"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- 引入我们自己编写的每一个接口的实现文件 -->
  <mappers>
    <!--resource:表示从类路径下找资源  -->
    <mapper resource="mybatis/EmployeeDao.xml"/>
  </mappers>

</configuration>

EmployeeDao.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">

<!--namespace:名称空间;写接口的全类名,相当于告诉MyBatis这个配置文件是实现哪个接口的;  -->
<mapper namespace="com.atguigu.dao.EmployeeDao">

<!-- public Employee getEmpById(Integer id); -->
 <!-- 
 select:用来定义一个查询操作   
 id:方法名,相当于这个配置是对于某个方法的实现 
 resultType:指定方法运行后的返回值类型;(查询操作必须指定的)
 #{属性名}:代表取出传递过来的某个参数的值
 -->
 
  <select id="getEmpById" resultType="com.atguigu.bean.Employee">
    select * from t_employee where id=#{id}
  </select>
</mapper>

MyBatisTest.java

package com.atguigu.test;

import java.io.IOException;
import java.io.InputStream;

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 org.junit.Test;

import com.atguigu.bean.Employee;
import com.atguigu.dao.EmployeeDao;

public class MyBatisTest {

	@Test
	public void test() throws IOException {
		//1、根据全局配置文件创建出一个SqlSessionFactory
		//SqlSessionFactory:是SqlSession工厂,负责创建SqlSession对象;
		//SqlSession:sql会话(代表和数据库的一次会话);
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

		Employee employee;
		//2、获取和数据库的一次会话;getConnection();
		SqlSession openSession=sqlSessionFactory.openSession();
		try {
			//3、使用SqlSession操作数据库,获取到dao接口的实现
			EmployeeDao employeeDao = openSession.getMapper(EmployeeDao.class);
			//4、调用之前的方法
			employee = employeeDao.getEmpById(1);
		} finally{
			openSession.close();
		}
		System.out.println(employee);
	}
}

Published 434 original articles · won praise 105 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_39368007/article/details/104940330