Mybatis框架


一、Mybatis是什么?

简而言之,Mybatis,其本质,就是换了一种方式做增删改查。
mybatis-3.2.7.jar,Mybatis 框架最终会被封装一个 jar 包,解压后就是很多类,所谓的框架,其本质就是类。从文件的命名上可以看的出来,Mybatis 是由 apache 这个组织提供的一个技术,原名叫ibatis。

二、实现步骤

1.配置文件

<?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="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

2.映射文件

<?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">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" parameterType="int" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

三、具体代码

1. 测试类

package com.mybatis.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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 org.junit.Test;

import com.mybatis.bean.Flower;

/**
 1. 用Mybatis做的增删改查
 2. @author Lenovo
 3.  */
public class MybatisCRUD {

	//连接数据库
	public SqlSession getConnDBByMyBatis() throws IOException {
		String resource = "xiangge.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sfbqq = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = sfbqq.openSession();
		return session;
	}
	/**
	 * 增加
	 * 注意:用Mybatis做增删改时,需要提交事务
	 * @throws IOException
	 */
	@Test
	public void insertInfoByMyBatis() throws IOException {	
		SqlSession sessionSunchen = this.getConnDBByMyBatis();
		int data = sessionSunchen.insert("com.mybatis.dao.FlowerDao.insertID");
		System.out.println("data:"+data);
		if(data>0){
			sessionSunchen.commit();
			System.out.println("增加成功!");
			this.selectInfoByMyBatis();
		}else{
			System.out.println("增加失败!");
			sessionSunchen.rollback();
		}
	}
	/**
	 * 增加,带参数的增加
	 * alt+/;方法自动补全
	 * Shift+alt+L:接收对象的返回值
	 * @throws IOException
	 */
	@Test
	public void insertInfoByParam() throws IOException {
		SqlSession sesion = this.getConnDBByMyBatis();
		//此处稍后需要修改
		Flower flower = new Flower();
		flower.setName("教父");
		flower.setPrice(1.8f);
		flower.setProduction("马龙白兰度");
		
		sesion.insert("com.mybatis.dao.FlowerDao.insertInfoByParam", flower);
		sesion.commit();
		this.selectInfoByMyBatis();
	}
	
	//删除
	@Test
	public void deleteInfo() throws IOException {
		SqlSession session = this.getConnDBByMyBatis();
		session.delete("com.mybatis.dao.FlowerDao.deleteInfo");
		session.commit();
		this.selectInfoByMyBatis();
	}
	/**
	 * 删除;带有参数的删除
	 * @throws IOException
	 */
	@Test
	public void deleteInfoByID() throws IOException {
		int id = 17;
		SqlSession session = this.getConnDBByMyBatis();
		session.delete("com.mybatis.dao.FlowerDao.deleteInfoByID", id);
		session.commit();
		this.selectInfoByMyBatis();
	}
	
	//修改
	@Test
	public void updateInfo() throws IOException {
		SqlSession session = this.getConnDBByMyBatis();
		session.update("com.mybatis.dao.FlowerDao.updateInfo");
		session.commit();
		this.selectInfoByMyBatis();
	}
	/**
	 * 修改;带有参数的修改
	 * @throws IOException
	 */
	@Test
	public void updateInfoByParam() throws IOException {
		SqlSession session = this.getConnDBByMyBatis();
		Flower flower = new Flower();
		
		flower.setId(5);
		flower.setName("火苗");
		flower.setPrice(1.5f);
		flower.setProduction("格格");
		
		session.update("com.mybatis.dao.FlowerDao.updateInfoByParam", flower);
		session.commit();
		this.selectInfoByMyBatis();
	}
	
	//查询
	@Test
	public void selectInfoByMyBatis() throws IOException {
		//稍后在次数补上查询方法
		SqlSession session = this.getConnDBByMyBatis();
		List<Object> list = session.selectList("com.mybatis.dao.FlowerDao.selectZCID");
		for (Object longge : list) {
			System.out.println(longge);
		}
		session.close();
	}
	/**
	 * 查询一条数据
	 * @throws IOException 
	 */
	@Test
	public void selectById() throws IOException {
		SqlSession session = this.getConnDBByMyBatis();
		int id = 6;
		Object obj = session.selectOne("com.mybatis.dao.FlowerDao.selectById", id);
		System.out.println(obj);
		session.close();	
	}
	
}

2.com.mybatis.dao(映射文件)

<?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">
<mapper namespace="com.mybatis.dao.FlowerDao">
  <!-- 后边就是在这个文件中,补充增删改查对应的sql语句 -->
  <!-- 增加 -->
  <insert id="insertID">
  	INSERT INTO flower(`name`,price,production) VALUES('月亮之上','2.5','凤凰传奇');
  </insert>
  <!-- 增加;带参数的增加;#{}Mybatis中占位符 -->
  <insert id="insertInfoByParam" parameterType="com.mybatis.bean.Flower">
  	INSERT INTO flower(`name`,price,production) VALUES(#{name},#{price},#{production});
  </insert>
  <!-- 删除 -->
  <delete id="deleteInfo">
  	DELETE	FROM flower WHERE id=16
  </delete>
  
   <!-- 删除;通过ID删除 -->
  <delete id="deleteInfoByID" parameterType="java.lang.Integer">
  	DELETE	FROM flower WHERE id=#{id}
  </delete>
  
  <!-- 修改 -->
  <update id="updateInfo">
  	UPDATE flower SET `name`='浪漫樱花',price='1.9',production='郭富城' WHERE id=11
  </update>
  
  <!-- 修改;带有参数的修改 -->
  <update id="updateInfoByParam" parameterType="com.mybatis.bean.Flower">
  	UPDATE flower SET `name`=#{name},price=#{price},production=#{production} WHERE id=#{id}
  </update>
  
  <!-- 查询 -->
  <select id="selectZCID" resultType="com.mybatis.bean.Flower">
    SELECT * FROM flower;
  </select>
  <!-- 查询;用ID编号来查询 -->
  <select id="selectById" parameterType="java.lang.Integer" resultType="com.mybatis.bean.Flower">
  	SELECT * FROM flower WHERE id=#{id}
  </select>
</mapper>

3. 配置文件

<?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://127.0.0.1:3306/flowerdb6-20"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
  <!-- 这里需要关联上映射文件 -->
    <mapper resource="com/mybatis/dao/FlowerDao.xml"/>
  </mappers>
</configuration>

3. com.mybatis.bean(属性文件)

package com.mybatis.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Flower {

	private int id;
	private String name;
	private float price;
	private String production;
	
}

总结

第一步:创建项目并导包

  1. mybatis-3.2.7.jar:Mybatis 框架的核心包
  2. mysql-connector-java-5.1.30.jar。MySQL 驱动包,用于连接数据库
  3. lombok.jar,小辣椒包,用于封装实体类

第二步:创建分层开发需要包+类+方法等

第三步:在 src 文件夹下创建 Mybatis“配置文件”

第四步:在 dao 层中,创建“映射文件”

第五步:在增删改查测试类中用注释搭好架子,增删改查和连接数据库的方法写好。

第六步:开始执行增删改查相关方法

  1. 用 getConnDBByMyBatis 连接数据库
  2. 在配置文件中关联上映射文件
  3. 在映射文件中加上 sql 语句
  4. 用 session 对象调用相应增删改查方法
  5. 将返回结果打印到控制台中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

资深韭菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值