初探MyBatis之HelloWorld(一)

 

官方地址:https://github.com/mybatis/mybatis-3

准备:

官方中文文档地址:http://www.mybatis.org/mybatis-3/zh/getting-started.html

1、导入MyBatis的jar包和mysql连接驱动(maven):

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>

2、新建数据库和表,并在表中插入几条测试数据:

3、创建javabean对应数据表:

Employee.java:

 1 package yyc.mybatis.bean;
 2 
 3 public class Employee {
 4     private Integer id;
 5     private String lastName;
 6     private char gender;
 7     private String email;
 8     public Integer getId() {
 9         return id;
10     }
11     public void setId(Integer id) {
12         this.id = id;
13     }
14     
15     public String getLastName() {
16         return lastName;
17     }
18     public void setLastName(String lastName) {
19         this.lastName = lastName;
20     }
21     public char getGender() {
22         return gender;
23     }
24     public void setGender(char gender) {
25         this.gender = gender;
26     }
27     public String getEmail() {
28         return email;
29     }
30     public void setEmail(String email) {
31         this.email = email;
32     }
33     @Override
34     public String toString() {
35         return "Employee [id=" + id + ", lastName=" + lastName + ", gender=" + gender + ", email=" + email + "]";
36     }
37     
38 }
Employee.java

一、使用 XML 构建 SqlSessionFactory

 官方文档中给的是:

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

我在这里将它封装为一个类的静态方法:

MySqlSessionFacoty.java:

 1 package yyc.mybatis.util;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.apache.ibatis.io.Resources;
 7 import org.apache.ibatis.session.SqlSessionFactory;
 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 9 
10 public class MySqlSessionFacoty {
11     
12     public static SqlSessionFactory getSqlSessionFactory() throws IOException{
13         String resource = "mybatis-config.xml";
14         InputStream inputStream = Resources.getResourceAsStream(resource);
15         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
16         return sqlSessionFactory;
17     }
18 }
MySqlSessionFacoty.java

映射SQL语句:

EmployeeMapperXml.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">
<mapper namespace="yyc.mybatis.EmployeeMapper">
<!-- 
resultType:返回类型
#{id}:从传递过来的参数中获取id值
 -->
  <select id="selectEmp" resultType="yyc.mybatis.bean.Employee">
    select id,last_name lastName,gender,email from tb1_employee where id = #{id}
  </select>
</mapper>

XML 配置文件(configuration XML)中包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器(TransactionManager)。

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:///mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 将我们写好的sql映射文件注册到全局配置文件中 -->
  <mappers>
      <!-- xml映射配置方式 -->
    <mapper resource="EmployeeMapperXml.xml"/>
  </mappers>
</configuration>

测试方法:

    /**
     * 1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
     * 2.sql配置文件:配置了每一个sql,以及sql的封装规则
     * 3.将sql配置文件注册在全局配置文件
     * 4.写代码:
     *     (1)、根据全局配置文件得到SqlSessionFactory对象
     *     (2)、使用SqlSessionFactory获取sqlsession,使用它来实现crud
     *         一个sqlsession就是代表和数据库的一次会话,用完关闭
     * @throws IOException
     */
    @Test
    public void testXml() throws IOException{

        SqlSessionFactory sqlSessionFactory = MySqlSessionFacoty.getSqlSessionFactory();
    
    
        //2.获取sqlSession实例,能直接执行已经映射的sql语句
        SqlSession openSession = sqlSessionFactory.openSession();
        
        try {
            //1.唯一标识符(namespace + id)
            //2.执行sql需要用到的参数
            Employee employee = openSession.selectOne("yyc.mybatis.EmployeeMapper.selectEmp", 1);
            System.out.println(employee);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            openSession.close();
        }
        
    }

输出:

Employee [id=1, lastName=tom, gender=0, email=aa@163.com]
posted @ 2017-04-16 12:24  敲代码的小松鼠  阅读(1835)  评论(0编辑  收藏  举报

你若不想做,总会找到“接口”;你若想做,总会找到“方法”。