mybatis入门

mybatis入门

环境

MyEclipse14、Mysql 5.5、MyBatis 3.4.4

所需jar文件:

以及数据库连接驱动:mysql-connector-java-5.1.7-bin.jar

项目工程结构


需求背景
(1)根据用户id查询用户信息
(2)根据用户姓名模糊查询用户信息
(3)更新用户信息

创建全局配置文件SqlMapConfig.xml

配置MyBatis运行环境,数据源、事务等。

<?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?useUnicode=true&amp;characterEncoding=UTF8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
</configuration>


创建javaBean对象user.java

package com.hl.myabtis.first.beas;

import java.util.Date;

public class User {

    private int id;
    private String username;
    private char sex;
    private Date birthday;
    private String address;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public char getSex() {
        return sex;
    }
    public void setSex(char sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

}


创建映射文件User.xml

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 对sql进行分开处理,隔离 -->
<mapper namespace="test">
    <!-- 执行数据库的查询 ID用来标识次sql语句,称为Statement的ID #{}表示一个占位符 parameterType指定输入参数类型 id:接收参数名叫id,如果参数为简单类型,参数名随意 resultType:输出结果的类型 -->
    <select id="findUserById" parameterType="int" resultType="com.hl.myabtis.first.beas.User">
        select * FROM user WHERE id = #{id}
    </select>
</mapper>


主配置文件中加载映射文件

<?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?useUnicode=true&amp;characterEncoding=UTF8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 加载映射文件 -->
  <mappers>
    <mapper resource="sqlmap/user.xml"/>
  </mappers>
</configuration>


测试代码:

package com.hl.mybatis.first;

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.hl.myabtis.first.beas.User;

public class MyBatisFirst {

    @Test
    public void testFindUserById() throws Exception{
        //创建会话工厂
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource );
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过工厂得到SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //使用SqlSession操作数据库
        /** * 第一个参数是statement的ID,等于命名空间+id * 第二个参数是传递的参数,指定与映射文件中parameterType匹配的类型参数 */
        User user = sqlSession.selectOne("test.findUserById", 3);
        System.out.println(user);
        //关闭资源
        sqlSession.close();
    }
}


测试结果:

DEBUG [main] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - PooledDataSource forcefully closed/removed all connections.
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1440754855.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@55e02ca7]
DEBUG [main] - ==>  Preparing: select * FROM user WHERE id = ? 
DEBUG [main] - ==> Parameters: 3(Integer)
DEBUG [main] - <==      Total: 1
User [id=3, username=项羽, sex=1, birthday=Wed Apr 05 00:00:00 CST 2017, address=秦时明月之万里长城]


验证:


全部源代码包含过程与jar:http://download.csdn.net/detail/leisure_life/9849076

你可能感兴趣的:(mybatis)