Java MyBatis3(1)入门

MyBatis3介绍

    mybatis就是一个封装来jdbc的持久层框架它和hibernate都属于ORM框架但是具体的说,hibernate是一个完全的orm框架mybatis是一个不完全的orm框架

    Mybatis让程序员只关注sql本身而不需要去关注如连接的创建、statement的创建等操作

    Mybatis会将输入参数、输出结果进行映射。

MyBatis3原理

 

1、mybatis配置

    SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。

    mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。

 2、通过mybatis环境等配置信息构造SqlSessionFactory即会话工厂

 3、由会话工厂创建sqlSession即会话,操作数据库需要通过sqlSession进行。

 4、mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。

 5、Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。

 6、Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数。

 7、Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程。

MyBatis3入门使用

1.mysql表结构

 

创建表语句

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8

测试数据

insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('1','王五',NULL,'2',NULL);
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('10','张三','2014-07-10','1','北京市');
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('16','张小明',NULL,'1','北京市');
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('22','陈小明',NULL,'1','北京市');
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('24','张三丰',NULL,'1','北京市');
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('25','陈小明',NULL,'1','北京市');
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('26','王五',NULL,NULL,'北京市');
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('27','小六子',NULL,NULL,'北京市');
insert into `user` (`id`, `username`, `birthday`, `sex`, `address`) values('35','沐风',NULL,NULL,'北京市');

2.搭建如下工程

3.Mybatis的核心包和依赖包

4. User.java类

package com.mf.mybatis.po;

import java.io.Serializable;
import java.util.Date;


@SuppressWarnings("serial")
public class User implements Serializable{
	private int id;
	private String username;
	private String sex;
	private Date birthday;
	private String address;
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String 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;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex
				+ ", birthday=" + birthday + ", address=" + address + "]";
	}
	
}

5.创建全局配置文件

<?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"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>


    <mappers>
        <mapper resource="User.xml" />
    </mappers>
    
</configuration>

6.config目录下创建User.xml(这种命名规范是由ibatis遗留下来)

<?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="test">
    <select id="findUserById" parameterType="int" resultType="com.mf.mybatis.po.User">
        SELECT * FROM USER WHERE id =#{id}
    </select>
    
    <insert id="insertUser" parameterType="com.mf.mybatis.po.User">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID() 
        </selectKey>
    
        INSERT INTO USER
        (username,birthday,sex,address)
        VALUES(#{username},#{birthday},#{sex},#{address})
    </insert>
    
</mapper>

7.测试代码

package com.mf.mybatis.first;

import java.io.InputStream;
import java.util.List;

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.mf.mybatis.po.User;


public class MybatisFirst {

    @Test
    public void findUserByIdTest() throws Exception{
        //读取配置文件
        //全局配置文件的路径
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        
        //创建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        
        //创建SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        //调用SqlSession的增删改查方法
        //第一个参数:表示statement的唯一标示
        User user = sqlSession.selectOne("test.findUserById", 1);
        System.out.println(user);
        
        //关闭资源
        sqlSession.close();
    }
    

    @Test
    public void insertUserTest() throws Exception{
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        

        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        User user = new User();
        user.setUsername("沐风");
        user.setAddress("mufeng");
        

        sqlSession.insert("test.insertUser", user);
        
        System.out.println(user.getId());

        sqlSession.commit();

        sqlSession.close();
    } 
}

 

posted @ 2017-03-03 13:37  ~沐风  阅读(257)  评论(0编辑  收藏  举报