[数据库 05] Mybatis 入门


Mybatis入门


1. Mybatis使用

把SQL写入xml文件,降低sql和程序的耦合

最大的变化: 之前写UserDao接口之后写实现类UserDaoImp, 现在写UserMapper.xml配置文件


1. maven项目创建,添加依赖 mybatis

例子中,(创建的数据库名为mybatis,创建的表名为user)

2. 创建工具类

通过xml文件读入返回最后的SqlSession,类似于JDBC中的connection

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //固定写法,通过配置文件读入,从工厂建造得到工厂类
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();//从工厂类中获得sqlSession类(类似于得到数据库的连接connection类)
    }
}

3. 写mybatis-config.xml配置文件

配置文件中,修改四个变量为数据库连接,标签保留

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



    
        
            
            
                
                
                
                
            
        
    

    
        
    

4. 写实体类pojo.User

5. 写UserDao接口(之后改为UserMapper)

6. 写UserMapper.xml(相当于之前的UserDaoImp)

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

//相当于继承的接口
    

mapper添加到mybatis-config.xml配置文件中,配置文件添加:


     
    // 这里配置到UserMapper.xml的路径上,中间用/分开

7. test测试

测试需要先获得SqlSession对象,通过对象得到结果,并遍历

@Test
public void test(){
    SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtils.getSqlSession();// 从工具类获得数据库连接
            // 通过对接口的反射,获得接口的实现类,再new出一个实例对象
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            // 通过实例对象,调用方法,获得返回值
            List userList = mapper.getUserList();
		   // 遍历得到结果
            for (User user : userList) {
                System.out.println(user);
            }
        }finally {
            // 关闭数据库连接
            sqlSession.close();
        }
}

8. 注意点:

  1. 写的UserMapper.xml文件在java文件夹下,maven项目的pom.xml 配置文件中必须过滤java文件夹下的xml文件,保证顺利编译

    //maven的pom.xml配置
    
            
                
                    src/main/java
                    
                        **/*.xml
                        **/*.properties
                    
                
            
        
    
  2. mybatis-config.xml文件中添加写好的UserMapping.xml资源路径

    
        
    
    
  3. 提升变量作用域时,记得删除提升前的变量类型声明

2. CRUD

UserMapper.java:

public interface UserMapper {
    List getUserList();
    User getUserById(int id);
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);
}

UserMapper.xml 实现UserMapper接口

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


    
    




    
        insert into mybatis.user(`id`, `name`, `pwd`) values (#{id},#{name},#{pwd})
    

    
        update mybatis.user set `name`=#{name}, `pwd`=#{pwd} where `id`=#{id}
    

    
        delete mybatis.user where id = #{id}
    



1. select 查询

实现UserDao接口的xml文件:

写select标签,id为接口定义的方法名称, parameterType为传入的参数类型, resultType为返回值类型 如果是list,为list泛型的类型

 

测试类:

@Test
public void getUserById(){
    SqlSession sqlSession = null;
    try{
        sqlSession = MybatisUtils.getSqlSession();//获得数据库连接
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);// 通过反射获得接口类,实例化一个对象
        User userById = userMapper.getUserById(4);//调用函数并返回
        System.out.println(userById);
    }finally {
        sqlSession.close();
    }
}

Mybatis中,增删改的事务必须提交!!!!!

2. insert 插入





    
        insert into mybatis.user(`id`, `name`, `pwd`) values (#{id},#{name},#{pwd})
    

测试类:

@Test
    public void testOKInsert(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User insertUser = new User(4, "forth", "123");
        mapper.addUser(insertUser);
        sqlSession.commit();
        sqlSession.close();
    }

3. update 更新


    update mybatis.user set `name`=#{name}, `pwd`=#{pwd} where `id`=#{id}

测试类:

@Test
public void updateUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.updateUser(new User(4, "afterUpdate", "999"));
    sqlSession.commit();
    sqlSession.close();
}

4. delete 删除


    delete mybatis.user where id = #{id}

测试类:

@Test
public void deleteUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.deleteUser(4);
    sqlSession.commit();
    sqlSession.close();
}

3. Map 和 模糊查询

1. Map使用

当一个数据库属性很多时,插入语句中的字段往往需要一一对应,此时可以使用map

优点:xml文件中的value值不需要和数据库数据库中的一一对应,和map的key值对应就ok

  1. UserMapper.java 接口:
int addUser2(Map map);
  1. UserMapper.xml 接口实现:

	insert into mybatis.user(`id`, `name`, `pwd`) values (#{key1_Userid},#{key2_UserName},#{key3_password})

  1. 测试类:
@Test
public void testaddUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map map = new HashMap();
    map.put("key1_Userid", 5);
    map.put("key2_UserName", "keyvalue");
    map.put("key3_password", "mapPassword");
    mapper.addUser2(map);
    sqlSession.commit();
    sqlSession.close();
}

UserMapper.xml中传递参数:

  1. 如果只有一个参数,parameterType可以不写!!!,例如根据id查询的方法
  2. 如果参数是实体类,sql语句中的取值必须和属性对应
  3. 如果参数是map,sql语句中的取值为map的key值

2. 模糊查询

模糊查询的实现,在测试类中传入参数:

当测试类中,调用UserMapper.xml中的方法:

List userList = mapper.getUserLike("李%");//会去通配所有姓李的人

或者在.xml中定义:(id,定义传入参数是String,eg传入"1"时,可以使用,如果pT为int则不行)