MyBatis(1)-简单入门

时间:2021-09-19 16:53:41

简介

什么是 MyBatis ?

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github

 

简单的实例我们开始入门把

1).首先创建我们需要使用到的数据库(看截图,笔者所写的简单的截图),mysql数据库

MyBatis(1)-简单入门

2).创建一个简单的java工程,具体的目录如下

MyBatis(1)-简单入门

在lib文件下,导入三个jar包:

mybatis需要jar包:mybatis-3.4.6.jar

mysql驱动jar包:mysql-connector-java-5.1.17.-bin.jar

日志记录jar包:log4j-1.2.17.jar

3)一些文件的基本配置

log4j.xml配置文件的内容

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   </layout>
 </appender>
 <logger name="java.sql">
   <level value="debug" />
 </logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 </logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 </root>
</log4j:configuration> 

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" />
				<property name="username" value="root" />
				<property name="password" value="1234" />
			</dataSource>
		</environment>
	</environments>
	<!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
	<mappers>
		<mapper resource="EmployeeMapper.xml" />
	</mappers>
</configuration>

 Employee.java

package com.MrChengs.bean;

public class Employee {

	private int id;
	private String name;
	private String gender;
	private String email;
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", gender=" + gender + ", 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 getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

 EmployeeMapper.java

package com.MrChengs.dao;

import com.MrChengs.bean.Employee;

public interface EmployeeMapper {
	//查数据,封装为其对象
	//接口和文件进行动态绑定
	public Employee getEmployee(int id);
}

 MyBatisTest.java

package com.MrChengs.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.MrChengs.bean.Employee;
import com.MrChengs.dao.EmployeeMapper;

public class MyBatisTest {//原生态的编程方式
    @Test
    public void test() throws IOException {
        //1.根据xml文件的配置(全局文件)创建一个SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);        
        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) new 
                SqlSessionFactoryBuilder().build(inputStream);
        
        //2.获取SqlSession的实例,直接执行已经映射的sql语句
        //SqlSession是和数据库的一次会话
        //都是非线程安全的,每次使用都应该去获取新的对象
        //sql的唯一标识,
        //执行sql要用的参数
        SqlSession session = sqlSessionFactory.openSession();
        try{
            Employee employee =  session.selectOne("com.MrChengs.dao.EmployeeMapper.getId",5);
            System.out.println(employee);
        }finally{
            session.close();
        }
    }
    //定义共有的方法
    public SqlSessionFactory getSqlSessionFactory() throws IOException{ String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); }
//接口式的编程  
@Test
public void test1() throws IOException{
    
//1.得到SqlSeesionFactory SqlSessionFactory sessionFactory = getSqlSessionFactory();
    
//2.得到SqlSession SqlSession sqlSession = sessionFactory.openSession();
    try{
      //3.获取接口的实现类
      //会自动为接口创建一个代理对象,代理对象去增删改除
      //mapper接口没有实现类,但是Mybatishi生成一个代理的对象
      EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
      Employee employee
= mapper.getEmployee(5);
      System.
out.println(mapper.getClass());
      //class com.sun.proxy.$Proxy5
      System.out.println(employee);
      }
finally{
         sqlSession.close();
      }
} }

最终两个结果都是一样的:

MyBatis(1)-简单入门