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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值