MyBatis入门1

新建一个名为demo2的普通java项目, 我用的是idea


MyBatis入门1_第1张图片
image.png

在项目中新建lib文件夹, 将mybatis.jar,mysql-connector-java-5.1.45-bin.jar拷贝进去, 然后在项目中引用


MyBatis入门1_第2张图片
image.png

在src文件夹中新建config.xml文件,config文件里面都是mybatis的数据库信息和实体映射信息,




    
        
            
            
            
                
                
                
                
            
        
    
    
         
    

新建mybatisutil作为操作共用类

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author Paul.Huang
 * @data 2017/12/23 12:17
 * @Description
 */
public class MyBatisUtil {
    private final static SqlSessionFactory sqlSessionFactory;

    // 静态代码块加载mybatis-config.xml的配置文件
    static {
        String resource = "config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

实体类User

/**
 * @author gacl
 * users表所对应的实体类
 */
public class User {

    //实体类的属性和表的字段名称一一对应
    private int id;
    private String name;
    private int age;

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

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

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

数据库映射文件 userMapper.xml





    
    
    
    

MyBatis入门1_第3张图片
image.png

在Main类中调用

import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        SqlSession SqlselectOne = MyBatisUtil.getSqlSessionFactory().openSession();
        String name = "userMapper.getUser";
        User user = SqlselectOne.selectOne(name, 1);
        SqlselectOne.close();
        SqlSession SqlselectList = MyBatisUtil.getSqlSessionFactory().openSession();
        String allUser = "userMapper.getAllUsers";
        List users = SqlselectList.selectList(allUser);
        SqlselectList.close();
    }
}

你可能感兴趣的:(MyBatis入门1)