初识Mybatis

109 阅读2分钟

持久化 数据持久化

持久化就是将程序的数据在持久状态和瞬时状态转化的过程

内存:断电即失

数据库(jdbc),io文件持久化

生活:冷藏,罐头

为什么需要持久化? 有一些对象,不能让他丢掉

内存太贵

持久层 Dao层,Service层,Controller层

完成持久化工作的代码块

为什么需要Mybatis? 帮助我们将数据存入到数据库中

方便

传统的JDBC代码太复杂,简化,框架。自动化

不用Mybatis也可以,更容易上手。

第一个Mybatis程序 搭建环境

新建一个普通的maven项目,如下图:直接点击next创建一个普通的maven项目

image.png

`package com.ws.utils;

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;

//sqlSessionFactory ---> sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mybatis第一步获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (Exception e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }`

编写代码

1、实体类 `package com.ws.utils;

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;

//sqlSessionFactory ---> sqlSession public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { //使用Mybatis第一步获取sqlSessionFactory对象 String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (Exception e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }`

2、Dao接口

public interface UserDao { List getUserList(); }

3、接口实现类 从原来的UserDaoImpl转变成一个Mapper配置文件 `

select * from mybatis.user `
测试

注意:org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.

MapperRegistry是什么?

核心配置文件中注册mappers

3、CRUD(下面注意的是增删改查需要提交事务,否则不会执行) 1、namespace

namespace中的包名要和Dao/mapper接口包名一致!

2、select

选择,查询语句;

id:就是对应的namespace中的方法名

resultType:Sql语句执行的返回值!Class

parameterType:参数类型!

1、编写接口

//根据ID查询用户 User getUserById(int id);

2、编写对应的mapper中的sql语句

select * from mybatis.user where id = #{id}

3.测试

@Test public void getUserById(){ //获得SqlSession对象 SqlSession sqlSession = MybatisUtils.getSqlSession(); ​ UserMapper mapper = sqlSession.getMapper(UserMapper.class); ​ User user = mapper.getUserById(1); System.out.println(user); ​ //关闭SqlSession sqlSession.close(); } 3、Insert

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

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

5、Delete

delete from mybatis.user where id = #{id};

注意:增删改需要提交事务才能被响应到数据库!!!!!!!!!!