mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程)

  • 写在最前

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

  (了解更多,前往 http://www.mybatis.org/mybatis-3/zh/index.html

 

  • 提取准备需要用到的jar

  mybatis-3.2.4.jar 

  mysql-connector-java-5.1.33.jar  (下面示范用mysql)

 

  • 步骤预览

  (1)创建项目,添加mybatis配置文件 conf.xml

  (2)在数据库,新增一张简单用户表,然后创建用户实体类

  (3)定义操作用户表的sql映射文件UserMapper.xml

  (4)在conf.xml文件中注册UserMapper.xml

  (5)编写测试类进行测试

 

  • 项目结构一览

  

 

  • 开始体验

  1、创建java web项目,导入上面两个jar包

  

 

  添加配置文件conf.xml,路径:src/conf.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/test" />
                <property name="username" value="root" />
                <property name="password" value="123456" />                              
            </dataSource>
        </environment>
    </environments>   
</configuration>
conf.xml

 

  2、创建数据表 tb_user,添加测试数据

  

  新增实体类,路径:src/main/User.java

package main;

public class User {
   
    private int id;
    private String name;
    private int age;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}
User.java

 

  3、定义操作用户表的sql映射文件UserMapper.xml,路径: src/mapper/UserMapper.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="mapper.UserMapper">
    <select id="getUserById" parameterType="int" resultType="main.User">
        select * from tb_user where id = #{id}
    </select>
    
     <select id="getUserList" parameterType="int" resultType="main.User">
        select * from tb_user
    </select>    
</mapper>
UserMapper.xml

  注意配置路径!!!

 

  4、在conf.xml文件中注册UserMapper.xml,新增下面代码

     <mappers>
         <!-- 注册UserMapper.xml文件,-->         
         <mapper resource="mapper/UserMapper.xml"/>
     </mappers>

  完整代码:

<?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/test" />
                <property name="username" value="root" />
                <property name="password" value="123456" />                              
            </dataSource>
        </environment>
    </environments>   
    
     <mappers>
         <!-- 注册UserMapper.xml文件,-->         
         <mapper resource="mapper/UserMapper.xml"/>
     </mappers>

</configuration>
conf.xml

 

  5、测试,编写测试类Test1.java,路径:src/test/Test1.java

package test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import main.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test1 {

    public static void main(String[] args) throws IOException{
        
            // mybatis的配置文件
            String resource = "conf.xml";
            // 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
            InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
            // 构建sqlSession的工厂
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);                        
// 创建能执行映射文件中sql的sqlSession SqlSession session = sessionFactory.openSession(); String statement = "mapper.UserMapper.getUserById";// 映射sql的标识字符串 // 执行查询返回一个user对象 User user = session.selectOne(statement, 1); System.out.println("Result 1:"); System.out.println(user+"\n"); String statement2 = "mapper.UserMapper.getUserList";// 映射sql的标识字符串 List<User> users = session.selectList(statement2); System.out.println("Result 2:"); for (int i = 0; i < users.size(); i++) { //System.out.println(users.get(i).getName()); System.out.println(users.get(i)); } } }

  执行结果:

  

 

  (@_@)~到此结束~

 

posted @ 2017-06-30 16:33  lmei  阅读(648)  评论(0编辑  收藏  举报