-
Mybatis入门
一、Mybatis简介
1.1、简介
- Mybatis是一款优秀的持久层框架
- 支持自定义SQL、存储过程和高级映射。几乎免除了所有的JDBC代码和处理结果集代码。通过简单地XML或注解来配置。
1.2、持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(JDBC)、io持久化
为什么要持久化?
- 有一些对象,不能丢掉
- 内存太贵
1.3、持久层
Dao层、Service层、Controller层
- 完成持久化工作的代码
- 层界限十分明显
1.4、为什么使用Mybatis
-
帮助程序员将数据放到数据库中
-
方便
-
传统的JDBC代码太复杂,简化,框架,自动化
-
不用Mybatis也可以,用了更方便
-
优点:
- 简单易学
- 灵活
- sql与代码分离,提高了可维护性
- 提供映射标签,支持对象与数据库的orm字段关系映射
- 提供对象关系映射标签,支持对象关系组建维护
- 提供xml标签,支持编写动态sql
二、编写第一个Mybatis
2.1、搭建环境
-
创建一个普通的maven项目(作为父工程)
-
删除src目录,new Module作为子工程
-
导入依赖(mybatis、mysql、junit)
<dependencies> <!--mybatis驱动--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <!--junit驱动--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies>
2.2、创建new Module
-
编写Mybatis核心配置文件——mybatis-config.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/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/aishimin/dao/UserMapper.xml"/> </mappers> </configuration>
-
编写mybatis工具类获取SqlSession
package com.aishimin.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; public class MybatisUtils { static SqlSessionFactory sqlSessionFactory = null; static{ //使用mybatis步骤 //1、获取SqlSession String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //既然有了sqlSessionFactory实例,我们通过openSession可以获取SqlSession实例 // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
2.3、编写代码
- 编写实体类User
package com.aishimin.entity; public class User { private int id; private String name; private String pwd; public User(){}; public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } 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 String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
-
编写UserMapper接口(实际上就是MVC中的UserDao)
package com.aishimin.dao; import com.aishimin.entity.User; import java.util.List; public interface UserMapper { //查询所有用户,返回值为User结果集合 List<User> getUserList(); //通过id查找用户 User getUserById(int id); //增加用户 int addUser(User user); //更新用户 int updateUser(User user); //通过Id删除用户 int deleteUserById(int id); //模糊查询 List<User> getUserLike(Map<String,Object> map); }
-
编写UseMapper.xml其作用相当于UserMapper的实现类
<?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必须域类名对应一致 <mapper namespace="com.aishimin.dao.UserMapper"> //id为方法名 //resultType为结果返回类型 //parameterType为参数类型 <select id="getUserList" resultType="com.aishimin.entity.User"> select *from mybatis.user; </select> <select id="getUserById" parameterType="int" resultType="com.aishimin.entity.User"> select *from mybatis.user where id = #{id} </select> <insert id="addUser" parameterType="com.aishimin.entity.User"> insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd}); </insert> <update id="updateUser" parameterType="com.aishimin.entity.User"> update mybatis.user set name = #{name},pwd = #{pwd} where id = #{id}; </update> <delete id="deleteUserById" parameterType="int"> delete from user where id = #{id}; </delete> <select id="getUserLike" resultType="com.aishimin.entity.User" parameterType="map"> select *from mybatis.user where name like #{userid} </select> </mapper>
-
编写测试类
package com.aishimin.dao; import com.aishimin.entity.User; import com.aishimin.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; public class UserMapperTest { @Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUserList(); for(User user:userList){ System.out.println(user); } sqlSession.close(); } @Test public void testQuery(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(1); System.out.println(user); sqlSession.close(); } //增删改需要提交事务,否则数据库信息无法更新 @Test public void testInsert(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User(3,"娜美","123456789"); int res = mapper.addUser(user); if(res>0){ System.out.println("插入成功"); } sqlSession.commit(); sqlSession.close(); } @Test public void testUpdate(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.updateUser(new User(3,"乔巴","789456123")); if(res>0){ System.out.println("修改成功"); } sqlSession.commit(); sqlSession.close(); } @Test public void testDelete(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); int res = mapper.deleteUserById(3); if(res>0){ System.out.println("删除成功"); } sqlSession.commit(); sqlSession.close(); } //模糊查询 @Test public void testgetUserList(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String,Object> map = new HashMap<>(); map.put("userid","%路%"); List<User> users = mapper.getUserLike(map); for (User user:users){ System.out.println(user); } sqlSession.close(); } }
这里会遇到两个常见的错误,需要注意!
第一个错误:org.apache.ibatis.binding.BindingException: Type interface com.aishimin.dao.UserMapper is not known to the MapperRegistry.
遇到这个错误的原因是因为mybatis核心配置中没有注册mappers
需要在mybatis-config.xml中加入:
<mappers> <mapper resource="com/aishimin/dao/UserMapper.xml"/> </mappers>
遇到这个错误的原因是因为程序无法检测到我们编写的UserMapper.xml,需要在pom.xml中加入如下配置:
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
万能Mapper测试
这种方法属于野路子,适合于针对sql语句中参数较多的情况:
User getUserById2(Map<String,Object> map);
<select id="getUserById2" resultType="com.aishimin.entity.User" parameterType="map"> select *from mybatis.user where id = #{userid} </select>
@Test public void testQuery2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String,Object> map = new HashMap<>(); //Mapper传递参数只需要取出key即可 map.put("userid",2); User user = mapper.getUserById2(map); System.out.println(user); sqlSession.close(); }