简单易懂的Mybatis框架开发步骤,小白必看!!!

引言:MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。

1.导入常用jar包

	 <!-- mysql驱动依赖 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>8.0.22</version>
	</dependency>
	<!-- 数据源驱动依赖 -->
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>druid</artifactId>
		<version>1.2.4</version>
	</dependency>
	<!-- mybatis的核心依赖 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.5.6</version>
	</dependency>
	<!-- Junit测试依赖 -->
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>
	<!-- 日志依赖(不是主要依赖,可以不用添加)-->
	<dependency>
           <groupId>log4j</groupId>
           <artifactId>log4j</artifactId>
           <version>1.2.17</version>
       </dependency>

2.创建表以及实体类

1.在数据库中创建表

在这里插入图片描述

2.创建表的对应实体类

	public class Dept implements Serializable {
	
		private Integer id;
		private String name;
		private String loc;
		private String createby;
		private Date createtime;
	}

3.定义并配置mybatis的所有配置文件(重点)

1.创建数据源配置文件-druid.properties

	druid.url=jdbc:mysql://192.168.47.129:3306/emp_db?useUnicode=true&serverTimezone=Asia/Shanghai&useSSL=true
	druid.username=root
	druid.password=123

2.配置mybatis-configuration-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>
		<!-- 读取数据源的配置信息 -->
		<properties resource="config/druid.properties" />
		<typeAliases>
			<package name="com.ithouke.eimp.entity" />
		</typeAliases>
		<!-- 暂时用不到可以忽略 -->
		<plugins>
		<plugin interceptor="com.github.pagehelper.PageInterceptor">
	        <property name="reasonable" value="true"/>
	        <property name="helperDialect" value="mysql"/>             
	    </plugin>
		</plugins>
	
		<!--数据库的配置信息 -->
		<environments default="development">
			<environment id="development">
				<!--JDBC事务管理 -->
				<transactionManager type="JDBC" />
				<!---配置数据源信息 -->
				<dataSource type="com.ithouke.eimp.util.MybatisDataSource"> 		
					<property name="url" value="${druid.url}" />
					<property name="username" value="${druid.username}" />
					<property name="password" value="${druid.password}" />
				</dataSource>
			</environment>
		</environments>
	
		<!--配置表和类的映射文件 -->
		<mappers>
			<!-- 一个实体类,引入一个映射文件 -->
			<mapper resource="mapper/Dept.mapper.xml" />
			<mapper resource="mapper/Emp.mapper.xml" />
		</mappers>
	</configuration>
  • 上面数据源代码的解释

在这里插入图片描述

3.配置表和实体类的映射文件-mapper.xml(一个实体类一个映射文件)

	<?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">
	<!-- IDeptMapper的路径 -->
	<mapper namespace="com.ithouke.eimp.mapper.IDeptMapper">
		<!-- 定义映射规则 -->
		<resultMap type="Dept" id="deptMap">
			<!-- 主键用id -->
			<id property="id" column="dept_id" />
			<!-- 其他字段用result -->
			<result property="name" column="dept_name" />
			<result property="loc" column="dept_loc" />
			<result property="createby" column="dept_createby" />
			<result property="createtime" column="dept_createtime" />
		</resultMap>
		<!-- 定义插入语句 -->
		<insert id="save">
		 	<!-- 在SQL中使用#{}来对应 parameterType中的对应属性的值-->
			INSERT INTO
			dept_tab(dept_name,dept_loc,dept_createby,dept_createtime)
			VALUES(#{name},#{loc},#{createby},#{createtime})
		</insert>
		<!-- 定义删除语句 -->
		<delete id="delete">
			DELETE FROM dept_tab WHERE dept_id = #{id}
		<!-- 定义更新语句 -->
		</delete>
		<update id="update">
			UPDATE dept_tab SET dept_name
			=#{name},dept_loc=#{loc},dept_createby=#{createby},dept_createtime=#{createtime}
			WHERE dept_id = #{id}
		</update>
		<!-- 定义查询语句 -->
		<select id="findAll" resultMap="deptMap">
			SELECT * FROM dept_tab
		</select>
		<select id="findByName" resultMap="deptMap">
			SELECT * FROM dept_tab WHERE
			dept_name=#{name}
		</select>
		<select id="findForeach" resultMap="deptMap">
			SELECT * FROM dept_tab WHERE dept_loc IN
			<foreach collection="locs" item="loc" open="(" close=")"
				separator=",">
				#{loc}
			</foreach>
		</select>
	</mapper>

4.测试类

	public class TestHello {
		private SqlSession sqlSession;
		// @Test
		public void testSave() throws IOException {
			sqlSession = MybatisUtil.getInstance().getSqlSession();
			IDeptMapper mapper = sqlSession.getMapper(IDeptMapper.class);
			Dept dept = new Dept(null, "jjjjj", "kjhb", "jhg", new Date());
			mapper.save(dept);
			sqlSession.commit();
			sqlSession.close();
		}
		// @Test
		public void testFindAll() throws IOException {
			sqlSession = MybatisUtil.getInstance().getSqlSession();
			IDeptMapper mapper = sqlSession.getMapper(IDeptMapper.class);
			List<Dept> list = mapper.findAll();
			System.out.println(list);
			sqlSession.commit();
			sqlSession.close();
		}
		// @Test
		public void testDelete() throws IOException {
			sqlSession = MybatisUtil.getInstance().getSqlSession();
			IDeptMapper mapper = sqlSession.getMapper(IDeptMapper.class);
			mapper.delete(22);
			sqlSession.commit();
			sqlSession.close();
		}
		// @Test
		public void testUpdate() throws IOException {
			//从MyBatista类中获取对象
			sqlSession = MybatisUtil.getInstance().getSqlSession();
			//加载映射文件,得到一个mapper对象
			IDeptMapper mapper = sqlSession.getMapper(IDeptMapper.class);
			Dept dept = new Dept(24, "hkk", "kjhb", "jhg", new Date());
			//找到对应的SQL语句,并执行
			mapper.update(dept);
			//手动提交事务并关闭(DML语句必须手动提交,否则没效果)
			sqlSession.commit();
			sqlSession.close();
		}
	}
  • 附上Mybatis的工具抽取类代码:
	public class MybatisUtil {
	
		private SqlSessionFactory sqlSessionFactory;	
		private static final ReentrantLock lock = new ReentrantLock();	
		private static MybatisUtil instance;	
		public MybatisUtil() {
			try {	
			//加载主配置文件,创建一个sqlSessionFactory对象,相当于连接池对象
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-configuration.xml"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		public static MybatisUtil getInstance() {
			lock.lock();
			try {			
				if (instance == null ) {
					instance = new MybatisUtil();
				}
			} finally {
				lock.unlock();
			}
			return instance;	
		}
		创建SqlSession对象,相当于连接对象
		public SqlSession getSqlSession() {
			return sqlSessionFactory.openSession();		
		}
	}

5.MyBatis的运行流程:

1.加载配置文件:mybatis-config.xml
得到事务管理器,数据源信息,得到连接池对象,创建一个SqlSessionFactory对象(相当与一个连接池)
2.打开一个会话(和数据库的会话) SqlSession,相当于一个连接对象:Connection
3.使用SqlSession中的方法获取到映射文件中的SQL语句,并且执行SQL,获取到执行的结果
4.创建一个预编译语句对象,使用#{}指定的参数来作为SQL的参数,#{}取的是指定类型对象的属性值
执行SQL
5.查询操作的结果是一个结果集
此时需要将结果集数据封装成指定类型(使用resultType来指定)的对象
注意:此时要求Java中的对象的属性的类型(名称)必须和数据库中列的类型(名称)的一致

一个简单的MyBatis项目搭建完毕。除了上述的这些点之外,还有许多的知识点,如缓存、动态SQL、注解、等等,后面有时间了,我会进一步整理。

感谢大家的耐心阅读,如有不足,请多多指教!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值