MyBatis学习(二)

  上篇的实例主要是通过xml来了实现Mybatis的数据持久化的,这篇通过注解来简单实现一下。


一、基于注解实现

1、提供mapper文件


<span style="font-family:KaiTi_GB2312;font-size:18px;">public interface UserMapper {
		
	@Insert("insert into t_user (username,password,type) values(#{username},#{password},#{type})")
	public void add(User user);
			
	@Update("update t_user set password=#{password},username=#{username},type=#{type} where username=#{username}")
	public void update(User user);
			
	@Delete("delete from t_user where username=#{username}")
	public void delete(String username);
			
	@Select("select * from t_user")
	public List<User> userList();
}
</span>


2、主配置文件


<span style="font-family:KaiTi_GB2312;font-size:18px;">		<?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="jdbc.properties" />
			<!-- 确定包的地址 -->
			<typeAliases>
				<package name="itat.zttc.shop.model" />
			</typeAliases>
			<!-- 配置开发环境,默认的都是这个情况 -->
			<environments default="development">
				<environment id="development">
					<!-- 使用jdbc的事务管理 -->
					<transactionManager type="JDBC" />
					<dataSource type="POOLED">
						<property name="driver" value="${driver}" />
						<property name="url" value="${url}" />
						<property name="username" value="${username}" />
						<property name="password" value="${password}" />
					</dataSource>
				</environment>
			</environments>
			<!-- 将mapper文件加入到配置文件中 -->
			<mappers>
				<!-- 使用注解 -->
				<mapper class="itat.zttc.shop.mapper.UserMapper" />
			</mappers>
		</configuration>
</span>


3、MyBatisUtil(封装的读取xml,管理session的类)


<span style="font-family:KaiTi_GB2312;font-size:18px;">public class MyBatisUtil {
	private static SqlSessionFactory factory;
	static {
		try {
			InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
			factory = new SqlSessionFactoryBuilder().build(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static SqlSession createSession() {
		return factory.openSession();
	}
	
	public static void closeSession(SqlSession session) {
		if(session!=null) session.close();
	}
}</span>


4、客户端

<span style="font-family:KaiTi_GB2312;font-size:18px;">public class TestAnnotationMybatis {
	@Test
	public void testAddByAnnotation() {
		SqlSession session = null;
		try {
			session = MyBatisUtil.createSession();
			User user = new User();
			user.setUsername("testAnnotation");
			user.setPassword("testAnnotation");
			user.setType("testAnnotation");
			session.getMapper(UserMapper.class).add(user);
			session.commit();
			System.err.print("call the add");
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		} finally {
			MyBatisUtil.closeSession(session);
		}
	}

	@Test
	public void testUpdateAnnotation(){
		SqlSession session=null;
		
		try {
			session=MyBatisUtil.createSession();
			User user=new User();
			user.setUsername("testAnnotation");
			user.setPassword("updateUser");
			user.setType("updateuser");
			session.getMapper(UserMapper.class).update(user);
			session.commit();
			System.err.print("call the update");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.rollback();
		}finally{
			MyBatisUtil.closeSession(session);
		}
	}
	
	@Test
	public void testDeleteAnnotation() {
		SqlSession session = null;

		try {
			session = MyBatisUtil.createSession();
			User user = new User();
			user.setUsername("testAnnotation");
			session.getMapper(UserMapper.class).delete(user.getUsername());		
			session.commit();
			System.err.print("call the delete");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			session.rollback();
		} finally {
			MyBatisUtil.closeSession(session);
		}

	}

	@Test
	public void testSelectByAnnotation() {
		SqlSession session = null;
		try {
			session = MyBatisUtil.createSession();
			List<User> userList = session.getMapper(UserMapper.class).userList();
			for (User u : userList) {
				System.err.println("用户名称:" + u.getUsername());
			}

			session.commit();
			System.err.print("call the select");
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
		} finally {
			MyBatisUtil.closeSession(session);
		}
	}
}</span>



二、核心内容

    SqlSessionFactory :每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。
// 1、创建配置文件(mybatis-config.xml)的输入流
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
// 2、创建SQLSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

    SqlSession:SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
// 3、创建SQLSessioin
SqlSession session = factory.openSession();
// 4、调用mapper文件执行相应的操作(调用之前需要将mapper文件加入到mybatis-config.xml中)

    XML配置文件:数据库连接信息  +  mybatis的配置信息

<!-- 将mapper文件加入到配置文件中 -->
<mappers>
<!-- 使用配置文件 -->
<!-- <mapper resource="itat/zttc/shop/model/User.xml" /> -->
<!-- 使用注解 -->
<mapper class="itat.zttc.shop.mapper.UserMapper" />
</mappers>



三、小结

    纵观Mybatis主要内容,其原理和Hibernate的核心原理近乎相同,只不过Hibernate在对数据库的操作上封装的更彻底,而mybatis则需要自己去在xml中写sql语句,这大概是mybatis所谓的“半自动化持久框架”的原因吧。

PS:这里也只是简单的实践了一下Mybatis,如果往细处探究,在xml中使用if语句,choose,when,otherwise,还有foreach语句,这是Mybatis中比较让人头疼的一个地方,有兴趣的可以研究一下


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值