mybatis 学习记录(1)—— 入门程序

来源:互联网 发布:淘宝卖家有哪些活动 编辑:程序博客网 时间:2024/04/28 12:48

尊重个人劳动成果,转载请注明出处:
http://blog.csdn.net/czd3355/article/details/71241775

0.写在前面

本文仅介绍 mybatis 的入门级使用,即对单个表的增删改查操作。

1. 准备环境

  • IDEA 14.1.7
  • Mysql 5.5
  • maven

2. 数据库

学生表:stu
这里写图片描述

3. 配置文件

  • jdbc.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis01?useUnicode=true&characterEncoding=utf8jdbc.username=rootjdbc.password=335588

4. 项目结构

这里写图片描述

  • SqlMapConfig.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>    <!-- 加载属性文件 -->    <properties resource="jdbc.properties">        <!--配置数据库方言-->        <property name="dialect" value="mysql"/>    </properties>    <!-- 和spring整合后 environments配置将废除-->    <environments default="development">        <environment id="development">            <!-- 使用jdbc事务管理,事务控制由mybatis管理-->            <transactionManager type="JDBC"/>            <!-- 数据库连接池,由mybatis管理-->            <dataSource type="POOLED">                <property name="driver" value="${jdbc.driver}"/>                <property name="url" value="${jdbc.url}"/>                <property name="username" value="${jdbc.username}"/>                <property name="password" value="${jdbc.password}"/>            </dataSource>        </environment>    </environments>    <mappers>        <mapper resource="mapper/stu.xml"/>    </mappers></configuration>
  • stu 映射文件(stu.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="com.czd.mybatis01.dao.StudentDao">    <insert id="insertStudent" parameterType="com.czd.mybatis01.bean.Student">      INSERT stu(name)VALUES (#{name})    </insert>    <delete id="deleteStudent" parameterType="java.util.Map">        DELETE FROM stu WHERE `name` LIKE '${name}%'    </delete>    <update id="updateStudent" parameterType="com.czd.mybatis01.bean.Student">        UPDATE stu SET `name`=#{name} WHERE id=#{id}    </update>    <select id="findById" parameterType="java.lang.Integer" resultType="com.czd.mybatis01.bean.Student">      SELECT id,`name` FROM stu WHERE id=#{id}    </select>    <select id="findByName" parameterType="java.lang.String" resultType="com.czd.mybatis01.bean.Student">        SELECT id,`name` FROM stu WHERE `name`=#{name}    </select></mapper>
  • pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.czd.mybatis_test</groupId>    <artifactId>MybatisTest</artifactId>    <version>1.0-SNAPSHOT</version>    <dependencies>        <!-- 1. 日志 -->        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.17</version>        </dependency>        <!-- 2. 数据库 -->        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.37</version>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>c3p0</groupId>            <artifactId>c3p0</artifactId>            <version>0.9.1.2</version>        </dependency>        <!-- 3. MyBatis -->        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.3.0</version>        </dependency>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis-spring</artifactId>            <version>1.2.3</version>        </dependency>        <!-- 4. 测试 -->        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.12</version>            <scope>test</scope>        </dependency>    </dependencies></project>

5. java 代码

  • StudenDao 接口:
public interface StudentDao {    Student findById(int id);    Student findByName(String name);    void insertStudent(Student student);    void deleteStudent(String name);    void updateStudent(Student student);}
  • mybatis 工作流程:

    1. 通过 Reader 对象读取src目录下的 SqlMapConfig.xml 配置文件(该文本的位置和名字可任意)
    2. 通过 SqlSessionFactoryBuilder 对象创建 SqlSessionFactory 对象
    3. 从当前线程中获取 SqlSession 对象
    4. 通过 SqlSession 对象读取 stu.xml 映射文件中的 id,从而读取 sql 语句
    5. 事务提交,必写
    6. 关闭 SqlSession 对象,让 GC 尽早回收
  • 测试类:

package dao;import com.czd.mybatis01.bean.Student;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 java.io.Reader;import java.util.HashMap;import java.util.Map;/** * Created by czd on 2017/5/4. */public class StudentDao {    private static SqlSessionFactory sqlSessionFactory;    private static Reader reader;    private static String nameSpace = "com.czd.mybatis01.dao.StudentDao";    static {        try {            reader = Resources.getResourceAsReader("SqlMapConfig.xml");            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);        } catch (Exception e) {            e.printStackTrace();        }    }    public static SqlSessionFactory getSession() {        return sqlSessionFactory;    }    @Test    public void main() throws Exception {        StudentDao studentDao = new StudentDao();        // 增加//        Student student = new Student();//        student.setName("a");//        studentDao.testInsertStudent(student);        // 删除//        studentDao.testDeleteStudent("a");        // 更改//        Student student2 = new Student();//        student2.setId(2);//        student2.setName("czd2");//        studentDao.testUpdateStudent(student2);        // 根据id查询        System.out.println(studentDao.testFindById(1));        // 根据name查询        System.out.println(studentDao.testFindByName("czd2"));    }    public void testInsertStudent(Student student) throws Exception {        SqlSession sqlSession = getSession().openSession();        sqlSession.insert(nameSpace + ".insertStudent", student);        sqlSession.commit();        sqlSession.close();    }    public void testDeleteStudent(String name) throws Exception {        SqlSession sqlSession = getSession().openSession();        Map<String, String> map = new HashMap();        map.put("name", name);        sqlSession.delete(nameSpace + ".deleteStudent", map);        sqlSession.commit();        sqlSession.close();    }    public void testUpdateStudent(Student student) throws Exception {        SqlSession sqlSession = getSession().openSession();        sqlSession.insert(nameSpace + ".updateStudent", student);        sqlSession.commit();        sqlSession.close();    }    public Student testFindById(int id) throws Exception {        SqlSession sqlSession = getSession().openSession();        Student student = sqlSession.selectOne(nameSpace + ".findById", id);        sqlSession.commit();        sqlSession.close();        return student;    }    public Student testFindByName(String name) throws Exception {        SqlSession sqlSession = getSession().openSession();        Student student = sqlSession.selectOne(nameSpace + ".findByName", name);        sqlSession.commit();        sqlSession.close();        return student;    }}
1 0
原创粉丝点击