6.初识MyBatis

MyBatis是当前主流的Java持久层框架之一。

6.1什么是Mybatis

MyBatis框架也被称为ORM(对象关系映射)框架,所谓的ORM就是一种为了解决面向对象和关系型数据库数据类型不匹配的技术,通过描述Java对象与数据库表之间的映射关系,自动将Java应用程序中的对象持久化到关系型数据库的表中。
在这里插入图片描述
可以看出应用程序不在直接访问底层数据库,而是以面向对象的方式来操作持久化对象,ORM框架则通过映射将面向对象的操作转化成底层sql操作。
常见的ORM框架有Hibernate与MyBatis(1) Hibernate与MyBatis都可以是通过SessionFactoryBuider由XML配置文件生成SessionFactory,然后由SessionFactory 生成Session,最后由Session来开启执行事务和SQL语句。其中SessionFactoryBuider,SessionFactory,Session的生命周期都是差不多的。
(2) Hibernate和Mybatis都支持JDBC和JTA事务处理。

Hibernate的优势

Hibernate的DAO层开发比MyBatis简单,Mybatis需要维护SQL和结果映射。
Hibernate对对象的维护和缓存要比MyBatis好,对增删改查的对象的维护要方便。
Hibernate数据库移植性很好,MyBatis的数据库移植性不好,不同的数据库需要写不同SQL。
Hibernate有更好的二级缓存机制,可以使用第三方缓存。MyBatis本身提供的缓存机制不佳。
Mybatis优势
MyBatis可以进行更为细致的SQL优化,可以减少查询字段。
MyBatis容易掌握,而Hibernate门槛较高。
表关联较多,单一业务高并发的场景下不建议使用hibernate。

6.2Mybatis的下载和使用

在应用程序中引入MyBatis的核心包,并引入MySql数据库的驱动包。

6.3Mybatis的工作原理

在这里插入图片描述

6.4Mybatis的入门程序

6.4.1单个查询

一定先引入合适的jar包
首先创建testmybatis数据库,并创建表t_customer,有字段id username jobs phone。
由于Mybatis默认使用log4j输出日志信息,所以如果要查看控制台的输出sql语句,需要配置日志文件,log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

接着创建持久化类,其实持久化类和普通的javaBean并没有什么区别,只是其属性字段与数据库表字段相对应。

package com.itheima.po;

public class Customer {
    
    
	private Integer id;
	private String username;
	private String jobs;
	private Integer phone;
	public Integer getId() {
    
    
		return id;
	}
	public void setId(Integer id) {
    
    
		this.id = id;
	}
	public String getUsername() {
    
    
		return username;
	}
	public void setUsername(String username) {
    
    
		this.username = username;
	}
	public String getJobs() {
    
    
		return jobs;
	}
	public void setJobs(String jobs) {
    
    
		this.jobs = jobs;
	}
	public Integer getPhone() {
    
    
		return phone;
	}
	public void setPhone(Integer phone) {
    
    
		this.phone = phone;
	}
	@Override
	public String toString() {
    
    
		return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]";
	}
}

创建映射文件CustomerMapper映射文件

<?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.itheima.mapper.CustomerMapper">
	<select id="findCustomerById" parameterType="Integer"
	        resultType="com.itheima.po.Customer">
	        select * from t_account where id = #{id}
	 </select>
</mapper>

mapper是配置元素的根元素,namespace是指定了唯一的命名空间,通过包名+文件名组成。子元素selete是查询配置,id是唯一表示, parameterType表示输入参数类型,resultType表示输出类型,然后编写sql语句,其中 #{}表示占位符,相当于?,#{id}表示接收参数的名称为id。
然后创建核心配置文件,总计两步,第一步配置环境,然后配置mapper的位置

<?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>
    <!--1.配置环境 ,默认的环境id为mysql-->
    <environments default="mysql">
        <!--1.2.配置id为mysql的数据库环境 -->
        <environment id="mysql">
            <!-- 使用JDBC的事务管理 -->
            <transactionManager type="JDBC" />
            <!--数据库连接池 -->
            <dataSource type="POOLED">
			  <property name="driver" value="com.mysql.cj.jdbc.Driver" />
			  <property name="url" 
                            value="jdbc:mysql://localhost:3306/testmybatis?serverTimezone=UTC&amp;useSSL=false" />
			  <property name="username" value="root" />
			  <property name="password" value="1234" />
            </dataSource>
        </environment>
    </environments>
	<!--2.配置Mapper的位置 -->
	<mappers>
		<mapper resource="com/itheima/mapper/CustomerMapper.xml" />
	</mappers>
</configuration>

最后编写测试类

	public void findCustomerById() throws Exception{
    
    
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sessionFactory.openSession();
		String arg0 = "com.itheima.mapper.CustomerMapper.findCustomerById";
		Customer customer = session.selectOne(arg0,1);
		System.out.println(customer.toString());
		session.close();	
	}

程序运行结果如下
在这里插入图片描述

6.4.2增删改查

这样一旦学会了一个操作,其他的基本类似了
mapper文件如下

	<!-- 模糊查询 -->
	<select id="findCustomerByName" parameterType="String"
		resultType="com.itheima.po.Customer">
		select * from t_customer where username like concat('%',#{value},'%')
	</select>
		<!-- 添加 -->
	<insert id="addCustomer" parameterType="com.itheima.po.Customer">
		insert into t_customer(username,jobs,phone)
		values(#{username},#{jobs},#{phone})
	</insert>
	<!-- 更新 -->
	<update id="updateCustomer" parameterType="com.itheima.po.Customer">
	update t_customer set 
	username = #{username},jobs = #{jobs},phone = #{phone}
	where id = #{id}
	</update>
	<!-- 删除 -->
	<delete id="deleteCustomer" parameterType="Integer" >
	delete from t_customer where id = #{id}
	</delete>

只需要在测试类选择合适的输入参数和接收对象,就没问题

//	@Test
	public void findCustomerByName() throws Exception{
    
    
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sessionFactory.openSession();
		String arg0 = "com.itheima.mapper.CustomerMapper.findCustomerByName";
		List<Customer> customers = session.selectList(arg0,"a");
		for (Iterator iterator = customers.iterator(); iterator.hasNext();) {
    
    
			Customer customer2 = (Customer) iterator.next();
			System.out.println(customer2.toString());
		}
		session.close();	
	}
//	@Test
	public void addCustomer() throws Exception{
    
    
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sessionFactory.openSession();
		String arg0 = "com.itheima.mapper.CustomerMapper.addCustomer";
		Customer customer = new Customer();
		customer.setUsername("张大爷");
		customer.setJobs("拾大粪");
		customer.setPhone(128);
		int num = session.insert(arg0,customer);
		if (num>0) {
    
    
			System.out.print("成功插入"+num);
		}else
			System.out.print("失败");
		session.commit();
		session.close();	
	}
//	@Test
	public void updateCustomer() throws Exception{
    
    
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sessionFactory.openSession();
		String arg0 = "com.itheima.mapper.CustomerMapper.updateCustomer";
		Customer customer = new Customer();
		customer.setUsername("张大爷ye");
		customer.setJobs("拾大粪a");
		customer.setPhone(128);
		customer.setId(6);
		int num = session.update(arg0,customer);
		if (num>0) {
    
    
			System.out.print("成功修改"+num);
		}else
			System.out.print("失败");
		session.commit();
		session.close();	
	}
//	@Test
	public void deleteCustomer() throws Exception{
    
    
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sessionFactory.openSession();
		String arg0 = "com.itheima.mapper.CustomerMapper.deleteCustomer";
		int num = session.delete(arg0,1);
		if (num>0) {
    
    
			System.out.print("成功删除"+num);
		}else
			System.out.print("失败");
		session.commit();
		session.close();	
	}

猜你喜欢

转载自blog.csdn.net/q54188p/article/details/113585837