mybatis基本使用

Posted nhs3217

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis基本使用相关的知识,希望对你有一定的参考价值。

一、介绍

持久层框架

官方文档:http://www.mybatis.org/mybatis-3/zh/index.html

二、基本使用

1.创建项目和模块

2.添加pom.xml

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.1</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.17</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>

3.添加配置

resoucecs/mybatis-config.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>
    <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://192.168.137.101:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="mysql"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

4.创建库和表

mysql>create database mybatis ;
mysql>use mybatis ;
mysql>create table users(id int primary key auto_increment , name varchar(20) ,age int) ;
mysql>desc users ;

5.测试连接

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 java.io.IOException;
import java.io.InputStream;

public class App {
    public static void main(String[] args) {
        try {
            //指定配置文件的路径(类路径)
            String resource = "mybatis-config.xml";
            //加载文件
            InputStream inputStream = Resources.getResourceAsStream(resource);

            //创建会话工厂Builder,相当于连接池
            SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);

            //通过sf开启会话,相当于打开连接。
            SqlSession s = sf.openSession();
            System.out.println(s);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6.编写mapper文件

6.1)创建User类,和users对应

public class User {
    private Integer id ;
    private String name ;
    private int age ;
    //get/set
}

6.2)创建UserMapper.xml,存放在resources/目录下

resources/UserMapper.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="users">
    <!-- 定义insert语句 -->
    <insert id="insert">
      insert into users(name,age) values(#{name},#{age})
    </insert>
</mapper>

7.在resources/mybatis-config.xml文件中引入mapper的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>
    <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://192.168.137.101:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="mysql"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

8.编写单元测试,实现插入.

@Test
public void insert() throws Exception {
    //指定配置文件的路径(类路径)
    String resource = "mybatis-config.xml";
    //加载文件
    InputStream inputStream = Resources.getResourceAsStream(resource);

    //创建会话工厂Builder,相当于连接池
    SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);

    //通过sf开启会话,相当于打开连接。
    SqlSession s = sf.openSession();
    User u = new User();

    u.setName("jerry");
    u.setAge(2);
    s.insert("users.insert", u);
    s.commit();
    s.close();
}

9.完成update-selectOne-selectAll操作。

9.1)编写UserMapper.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="users">
    <insert id="insert">
      insert into users(name,age) values(#{name},#{age})
    </insert>
    <update id="update">
        update users set name = #{name} , age = #{age} where id = #{id}
    </update>

    <!-- selectOne -->
    <select id="selectOne" parameterType="int" resultType="com.niu.mybatisdemo.domain.User">
        select * from users where id = #{id}
    </select>

    <!-- selectAll -->
    <select id="selectAll" resultType="com.niu.mybatisdemo.domain.User">
        select * from users
    </select>
</mapper>

9.2)编写测试程序

@Test
public void insert() throws Exception {
    //指定配置文件的路径(类路径)
    String resource = "mybatis-config.xml";
    //加载文件
    InputStream inputStream = Resources.getResourceAsStream(resource);

    //创建会话工厂Builder,相当于连接池
    SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);

    //通过sf开启会话,相当于打开连接。
    SqlSession s = sf.openSession();
    User u = new User();

    u.setName("jerry");
    u.setAge(2);
    s.insert("users.insert", u);
    s.commit();
    s.close();
}
@Test
public void update() throws Exception {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession s = sf.openSession();
    User u = new User();
    u.setId(1);
    u.setName("tomas");
    u.setAge(32);
    s.update("users.update", u);
    s.commit();
    s.close();
}
@Test
public void selectOne() throws Exception {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession s = sf.openSession();
    User user = s.selectOne("users.selectOne",1);
    System.out.println(user.getName());
    s.commit();
    s.close();
}
@Test
public void selectAll() throws Exception {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession s = sf.openSession();
    List<User> users = s.selectList("users.selectAll");
    for(User uu : users){
        System.out.println(uu.getName() + "," + uu.getAge());
    }
    s.commit();
    s.close();
}

三、复杂应用

 

以上是关于mybatis基本使用的主要内容,如果未能解决你的问题,请参考以下文章

markdown [mybatis参考]关于mybatis #mybatis的一些片段

MYBATIS05_ifwherechoosewhentrimsetforEach标签sql片段

html PHP代码片段: - AJAX基本示例:此代码演示了使用PHP和JavaScript实现的基本AJAX功能。

mybatis 存储过程

mybatis学习(39):动态sql片段

使用mybatis的两种方式