17.Mybatis的基本使用及入门案例

 

一、什么是 MyBatis ?

  MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

二、入门案例

  maven工程样式

  

  创建maven工程,添加对应jar包(在pom.xml文件中插入)

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sxt</groupId>
  <artifactId>mybatis.01.hello</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.6</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.32</version>
      </dependency>
  </dependencies>
</project>

 

  创建全局配置文件,该配置文件包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器TransactionManager)。(文件命名为mybatis-cfg.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://localhost:3306/j0325?characterEncoding=utf-8"/>
        <property name="username" value="root"/>
        <property name="password" value="123"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
      <!-- 关联映射文件 -->
      <mapper resource="com/sxt/pojo/UserMapper.xml"/>
  </mappers>
</configuration>

  定义User对象

package com.sxt.pojo;

public class User {
    
    private Integer id;
    
    private String name;
    
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
    

}

  创建映射文件(文件命名为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">
<!-- namespace 名称空间:作用是用来区分各个xml映射文件 -->
<mapper namespace="com.sxt.pojo.User">
    <select id="query" resultType="com.sxt.pojo.User">
        select * from t_user
    </select>
    
    <insert id="addUser" parameterType="com.sxt.pojo.User">
        insert into t_user(name,age)values(#{name},#{age})
    </insert>
    
    <delete id="deleteById" parameterType="int">
        delete from t_user where id=#{id}
    </delete>
    
    <update id="updateUser" parameterType="com.sxt.pojo.User">
        update t_user set name=#{name} , age=#{age} where id=#{id}
    </update>
    
    <select id="queryById" resultType="com.sxt.pojo.User">
        select * from t_user where id = #{id}
    </select>
</mapper>

  测试

package com.sxt.test;

import java.io.IOException;
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.sxt.pojo.User;

public class MybatisTest01 {

    @Test
    public void query() throws IOException {
        
        InputStream in = Resources.getResourceAsStream("mybatis-cfg.xml");
    
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        
        SqlSession session = factory.openSession();
        
        List<User> list = session.selectList("com.sxt.pojo.User.query");
        for (User user : list) {
            System.out.println(user);
        }
        
        session.close();
    }

    @Test
    public void queryById() throws IOException {
        InputStream in = Resources.getResourceAsStream("mybatis-cfg.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session = factory.openSession();
        List<User> list = session.selectList("com.sxt.pojo.User.queryById", 1);
        for (User user : list) {
            System.out.println(user);
        }
        session.close();
    }
    
    @Test
    public void addUser() throws IOException {
        InputStream in = Resources.getResourceAsStream("mybatis-cfg.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session = factory.openSession();
        User user = new User();
        user.setName("wdh");
        user.setAge(18);
        int count = session.insert("com.sxt.pojo.User.addUser", user);
        session.commit();
        System.out.println("影响的行数:" + count);
        session.close();
    }
    
    @Test
    public void updateUser()throws IOException{
        InputStream in = Resources.getResourceAsStream("mybatis-cfg.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session = factory.openSession();
        User user = new User();
        user.setId(1);
        user.setName("cc");
        user.setAge(27);
        int count = session.insert("com.sxt.pojo.User.updateUser", user);
        session.commit();
        System.out.println("受影响的行数:"+count);
        session.close();
    }
    
    @Test
    public void deleteUser()throws IOException{
        InputStream in = Resources.getResourceAsStream("mybatis-cfg.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession session = factory.openSession();
        int count = session.insert("com.sxt.pojo.User.deleteById",1);
        session.commit();
        System.out.println("受影响的行数:"+count);
        session.close();
    }

    
}

posted @ 2019-07-11 17:38  69之王  阅读(214)  评论(0编辑  收藏  举报