一、mybatis搭建配置环境
1.导入jar包(坐标)



    4.0.0
    com.itheima
    kuangjia001
    1.0-SNAPSHOT
  
      
          org.mybatis
          mybatis
          3.5.0
      
    
        mysql
        mysql-connector-java
        5.1.47
    
    
        log4j
        log4j
        1.2.17
    
    
        junit
        junit
        4.12
        test
    
  

2.创建mybatis主配置文件
D:\黑马培训\ideal代码包\kuangjia001\src\main\resources\mybatis-config.xml




    
    
        
            
            
            
            
            
            
            
            
            
            
        
    
    
        
        
    

3.准备实体类和表结构
D:\黑马培训\ideal代码包\kuangjia001\src\main\java\com\itheima\domain\User.java

package com.itheima.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
    private Integer uid;//主键。类型要使用包装类型
    private String name;//登录名
    private String password;//密码
    private String email;//邮箱
    private String phoneNumber;//手机号
    private Date birthday;//生日
    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", birthday=" + birthday +
                '}';
    }
    public Integer getUid() {
        return uid;
    }
    public void setUid(Integer uid) {
        this.uid = uid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

4.创建Mapper接口(Dao接口)
D:\黑马培训\ideal代码包\kuangjia001\src\main\java\com\itheima\dao\UserMapper.java


public interface UserMapper {
    /**
     * 添加一条用户记录
     * @param user
     */
    void addUser(User user)
}

5.创建Mapper接口方法和SQL映射文件
D:\黑马培训\ideal代码包\kuangjia001\src\main\resources\mybatis-config.xml(映射文件与src\main\res)

?xml version="1.0" encoding="UTF-8" ?>



    
    //parameterType方法中输入值的类型
        INSERT into users (name,password,email,phoneNumber,birthday) values (#{name},#{password},#{email},#{phoneNumber},#{birthday});//#{name}相当于调用users.getname方法
    
    
    
    
        
        
        
        
        
        
        
    
    
    
    

6。将映射文件添加到Mybatis
D:\黑马培训\ideal代码包\kuangjia001\src\main\resources\mybatis-config.xml

二、入门案例一
1.案例一中主要的类和接口
Resources:加载mybatis配置文件。
SqlSessionFactoryBuilder:利用Resources指定的资源,将配置信息加载到内存中,还会加载所有的配置文件映射配置信息,并用特定的对象实例进行保存,从而创建SqlSessionFactory对象。
SqlSessionFactory:包含所有配置内容的对象,一个项目只用一个。
SqlSession:每个线程独有,用时打开,不用关闭。单独使用mybaits进行开发时最常用的接口。
openSession:获取SqlSessionFactory,返回一个SqlSession对象创建事务。底层是做各种成员变量的初始化。
BasemapperTest基类用于junit单元测试。
classloader:类加载器,将类加载到jvm 中。
Resources 类为从类路径中加载资源,提供了易于使用的方法。
? 从类路径加载 SQL Map 配置文件(如 sqlMap-config.xml)。
? 从类路径加载 DAO Manager 配置文件(如 dao.xml)
? 从类路径加载各种.properties 文件。
2.案例源码
2.1
01.mybatis 的Junit测试基类
1.获取配置文件的输入流
2.通过输入流获得sqlSessionFactoryBuilder工厂
3.创建openSession,获取SqlSessionFactory,返回一个SqlSession对象创建事务。

public class BaseMapperTest {
    private static SqlSessionFactory sqlSessionFactory;
    @BeforeClass//仅在加载类字节码时执行一次
    public static void init(){
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");//获取配置文件的输入流
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //SqlSessionFactoryBuilder:加载所有的配置文件映射配置信息,并用特定的对象实例进行保存,从而创建SqlSessionFactory对象。
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
    protected SqlSession openSession() {return sqlSessionFactory.openSession();}
}

02.测试编码模板


@Test
public void testAddUser3() throws Exception {
    SqlSession sqlSession = null;
    try {
        sqlSession = openSession();
        //获取UserMapper实例
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(userMapper.getClass().getCanonicalName());
        //调用方法
        User user = new User();
        user.setName("user4");
        user.setPassword("sorry");
        user.setEmail("[email protected]");
        user.setPhoneNumber("124");
        user.setBirthday(new Date());
        userMapper.addUser(user);
        //提交事务
        sqlSession.commit();
    }catch (Exception e){
        sqlSession.rollback();
        throw new RuntimeException(e);
    }finally{
        //释放资源
        sqlSession.close();
    }
}

2.2查询所有记录
resultMap映射结果集
com/itheima/dao/UserMapper.xml





    
    
    
    
    
    
    

//
    select uid as id,name username,password,email,phoneNumber,birthday from users

com.itheima.test.UserMapperTest

@Test
public void testFinaAllUsers() throws Exception {
    SqlSession sqlSession = null;
    try {
        sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List users = userMapper.findAllUsers();
        for(User user:users)
            System.out.println(user);
    }catch (Exception e){
        throw new RuntimeException(e);
    }finally{
        sqlSession.close();
    }
}

2.2查询一条记录
com/itheima/dao/UserMapper.xml


com.itheima.test.UserMapperTest


@Test
public void testFinaUserByUid() throws Exception {
    SqlSession sqlSession = null;
    try {
        sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findUserByUid(1);
        System.out.println(user);
    }catch (Exception e){
        throw new RuntimeException(e);
    }finally{
        sqlSession.close();
    }
}

2.3查询多条记录
com.itheima.dao.UserMapper

/**

  • 根据用户名和密码查询
  • @param name,password
  • @return
    */
    User findUserByNamePassword(@Param("name") String name,@Param("password") String password);

//设置param别名,与xml中的代码相联系。

com/itheima/dao/UserMapper.xml

com.itheima.test.UserMapperTest

@Test
public void testFinaUserByNamePassword() throws Exception {
    SqlSession sqlSession = null;
    try {
        sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findUserByNamePassword("admin","sorry");
        System.out.println(user);
    }catch (Exception e){
        throw new RuntimeException(e);
    }finally{
        sqlSession.close();
    }
}

2.4根据POJO查询
com.itheima.dao.UserMapper

/**
* 根据用户名和密码查询
* @param userVo
* @return
*/
User findUserByNamePassword1(User userVo);
com/itheima/dao/UserMapper.xml


com.itheima.test.UserMapperTest

@Test
public void testFinaUserByNamePassword1() throws Exception {
    SqlSession sqlSession = null;
    try {
        sqlSession = openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User userVo = new User();
        userVo.setName("admin");
        userVo.setPassword("sorry");
        User user = userMapper.findUserByNamePassword1(userVo);
        System.out.println(user);
    }catch (Exception e){
        throw new RuntimeException(e);
    }finally{
        sqlSession.close();
    }
}

2.5模糊查询
com.itheima.dao.UserMapper

01 List findUsersByName(String name);
02 List findUsersByName1(@Param("name") String name);
03 List findUsersByName2(String name);

com/itheima/dao/UserMapper.xml

01 select uid,name,password,email,phoneNumber,birthday from users where name like #{name}
02 select uid,name,password,email,phoneNumber,birthday from users where name like '%${name}%'
03 select uid,name,password,email,phoneNumber,birthday from users where name like concat('%',#{name},'%')

com.itheima.test.UserMapperTest

01 List users = userMapper.findUsersByName("%user%");
02 List users = userMapper.findUsersByName1("user");
03 List users = userMapper.findUsersByName2("user");

2.6获取自动生成的主键
com.itheima.dao.UserMapper


void addUser1(User user);
void addUser2(User user);

com/itheima/dao/UserMapper.xml




    INSERT into users (name,password,email,phoneNumber,birthday) values (#{name},#{password},#{email},#{phoneNumber},#{birthday});



    
    
        select last_insert_id()
    
    INSERT into users (name,password,email,phoneNumber,birthday) values (#{name},#{password},#{email},#{phoneNumber},#{birthday});

com.itheima.test.UserMapperTest

@Test
public void testAddUser6() throws Exception {
    SqlSession sqlSession = null;
    try {
        sqlSession = openSession();
        //获取UserMapper实例
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(userMapper.getClass().getCanonicalName());
        //调用方法
        User user = new User();
        user.setName("user10");
        user.setPassword("sorry");
        user.setEmail("[email protected]");
        user.setPhoneNumber("130");
        user.setBirthday(new Date());
        userMapper.addUser2(user);
        //提交事务
        sqlSession.commit();
        System.out.println(user);
    }catch (Exception e){
        sqlSession.rollback();
        throw new RuntimeException(e);
    }finally{
        //释放资源
        sqlSession.close();
    }
}

2.6修改和删除
com.itheima.dao.UserMapper


void updateUser(User user);
void deleteUserByUid(Integer uid);

com/itheima/dao/UserMapper.xml


    update users set name=#{name},password=#{password},email=#{email},phoneNumber=#{phoneNumber},birthday=#{birthday} where uid=#{uid}


    delete from users where uid=#{uid}

com.itheima.test.UserMapperTest


@Test
public void testDeleteUser() throws Exception {
    SqlSession sqlSession = null;
    try {
        sqlSession = openSession();
        //获取UserMapper实例
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        System.out.println(userMapper.getClass().getCanonicalName());
        userMapper.deleteUserByUid(9);
        sqlSession.commit();
    }catch (Exception e){
        throw new RuntimeException(e);
    }finally{
        sqlSession.close();
    }
}