mybatis学习第一次使用

mybatis学习第一天

  • 1.使用IDEA创建一个maven工程
  • 2.去百度mvn r.. https://mvnrepository.com/artifact/org.mybatis/mybatis/3.4.4 查找mybatits的maven包的结构
  • 3.http://www.mybatis.org/mybatis-3/zh/getting-started.html 跟着这个教程简单的实践一下如何简单的了解使用mybatits
  • 4.使用navicat 创建一个mybatis的数据库,创建一个简单的表进行实验

添加mybatis maven 配置

        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.4version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.40version>
        dependency>

创建数据库mybatis与之创建一个表user和对应的实体的文件信息

Create TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) ,
  `userAge` int(11) ,
  `userAddress` varchar(200),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Insert INTO `user` VALUES ('1', 'wangji', '25', 'guizhou');

创建与之对应的实体User

package com.jet.module.UserManage.entity;

/**
 * Created by JetWang on 2017/7/19.
 */
public class User {
    private int id;
    private String name;
    private Integer age;
    private String address;

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

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

配置mapping和Dao接口

说明一下,这里的mapping有点类似于Hibernate中Dao的实现,只是这个实现是在配置文件中去书写.

package com.jet.module.UserManage.dao;

import com.jet.module.UserManage.entity.User;

/**
 * Created by JetWang on 2017/7/19.
 */
public interface UserDao {
    User findById(Integer id);
}

mapping,可以想象为Dao具体的实现




<mapper namespace="com.jet.module.UserManage.dao.UserDao">
    
    
    <select id="findById" parameterType="int" resultType="User">
       select id,userName as name,userAge as age,userAddress as address from `user` where id = #{id}
    select>
mapper>

mybatis-config的属性配置直接去官方copy下来,对于学习来说,基本的配置属性基本够用了



<configuration>
    <typeAliases>
        <typeAlias alias="User" type="com.jet.module.UserManage.entity.User"/>
    typeAliases>
    <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://127.0.0.1:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="wang"/>
            dataSource>
        environment>
    environments>
    <mappers>
        
        <mapper resource="user-mapping.xml"/>
    mappers>
configuration>

mybatis学习第一次使用_第1张图片

然后就是写个测试,测试一下我们这个查找通过ID能不能成功。

基本的步骤就是获取配置文件中的属性来创建Session工程,然后获取一个Session,就可以通过命名空间进行查询或者通过Mapper进行查询。和JDBC中的Connection有点类似,与Hibernate中的Session一样的道理。(怎么去获取配置文件之类的官方文档很详细)

 import com.jet.module.UserManage.dao.UserDao;
import com.jet.module.UserManage.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by JetWang on 2017/7/19.
 */
public class UserDaoTest {

    @Test
    public void findByIdTest() {
        InputStream inputStream = null;
        SqlSessionFactory sqlSessionFactory = null;
        SqlSession sqlSession = null;
        try {
            inputStream = org.apache.ibatis.io.Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession = sqlSessionFactory.openSession();
            //这里面向接口的,mybatis使用动态代理给你生成实现类,不需要DaoImpl
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            User user = userDao.findById(1);
          /*
          通过命名空间进行查询
          User user = sqlSession.selectOne("com.jet.module.UserManage.dao.UserDao.findById",1);
          */
            Assert.assertNotNull(user);
            System.out.println(user.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}

好好动起来,可以了

mybatis学习第一次使用_第2张图片

地址: https://github.com/WangJi92/mybatits-study/blob/master/mybatis-study/study-1

你可能感兴趣的:(mybatis)