Mybatis 学习笔记—— 基础方式的CRUD

Posted Johnny*

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis 学习笔记—— 基础方式的CRUD相关的知识,希望对你有一定的参考价值。

Mybatis

Mybatis(前身ibatis,2010被Google收购后改名为mybatis)是一个支持普通SQL查询、存储过程以及高级映射的持久层框架。Mybatis是一种ORM(Object/Relational Mapping)框架,它通过描述Java对象与数据库表之间的映射关系,自动将Java应用程序中的对象持久化到关系型数据库表中。

在这里插入图片描述

入门示例

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/goodsadmin"/>
		 <property name="username" value="root"/>
		 <property name="password" value="120329"/>
		 </dataSource>
	 </environment>
 </environments>
 <mappers>
 	<mapper resource="com/johnny/entity/personMapper.xml"/>
 </mappers>
</configuration>

personMapper.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">
 
<mapper namespace="com.johnny.personMapper">
	 <select id="selectPersonById" resultType="com.johnny.entity.Person">
	 	select * from person where id = #{id}
	 </select>
</mapper>

实体类Person.java,其属性与数据库中的表person 的字段相对应

package com.johnny.entity;

public class Person {
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return this.id+","+ this.name+", " +this.age;
	}
	private int id;
	private String name;
	private int age;
	

}

person表
在这里插入图片描述

测试类

package com.johnny.entity;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class TestMybatis {

	public static void main(String[] args) throws IOException {
		
		//1、加载资源文件:获取mybatis配置文件输入流/MybatisDemo0/src/com/johnny/entity/config.xml
		InputStream in = Resources.getResourceAsStream("config.xml");
		//2、 通过 SqlSessionFactoryBuilder 获得SqlSessionFactory 的实例
		SqlSessionFactory sqlFactory =  new SqlSessionFactoryBuilder().build(in);
		
		//3、获取session对象 --相当于JDBC中的Connection对象
		SqlSession session = sqlFactory.openSession();
		//xml命名空间+sql语句id
		String statement = "com.johnny.personMapper.selectPersonById";
		Person per = session.selectOne(statement,1);
		System.out.println(per);
		
		

	}

}

  1. 配置mybatis配置文件config.xml,改文件中配置数据库信息和需要加载的映射文件
  2. 将表和实体通过xxxMapper.xml 关联其阿里
  3. 测试类通过sqlsessionFactory获取session对象。

使用mybatis实现增删改查

  1. 输入参数parameterType和输出参数resultType 在形式上只能有一个
  2. 如果输入参数是简单类型(8个基本数据类型 + String),则可以使用任意占位符 #{xx}。但是如果是对象类型则必须是对象的属性 #{属性名}
  3. 返回类型。不论返回值是一个还是多个,resultType只需指定元素的类型即可,不用集合。

personManager.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">
 
<mapper namespace="com.johnny.personMapper">  <!-- 该mapper的命名空间 -->
	
	 <select id="selectPersonById" resultType="com.johnny.entity.Person">
	 	select * from person where id = #{id}
	 </select>
	 
	 <select id="selectAllPerson" resultType="com.johnny.entity.Person">
	 	select * from person 
	 </select>
	 
	 <insert id="addPerson" parameterType="com.johnny.entity.Person">
	 	insert into person(id, age, name)  values( #{id}, #{age}, #{name})
	 </insert>
	 
	 <update id="updatePerson" parameterType ="com.johnny.entity.Person">
	 	update person set name = #{name}, age =#{age} where id = #{id} 
	 </update>
	 
	 <delete id="deletePersonById" parameterType ="int">
	 	delete from person where id=#{id}
	 </delete>
	 
	 
</mapper>

配置文件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">
 	<!-- 通过environments 的 default 和 enviroment的id 来指定数据库环境 -->
	 <environment id="development">
	 <!-- transactionManager 事务提交方式
	 	JDBC : 利用JDBC 方式处理事务 (rollback、commit、close) 
	  	MANAGED: 将事务交由其他组件(如spring、jobss)去托管,默认会关闭连接
	  		<property name = "closeConnection" value ="false"/> 来指定不关闭
	  -->
	 <transactionManager type="JDBC"/>
	 	<!-- 数据源类型:
	 		UNPOOLED: 传统的JDBC模式(每次访问数据库需要打开、关闭数据操作,比较消耗性能)
	 		POOLED : 使用数据库连接池方式
	 		JNDI: 从tomcat中获取一个内置的数据库连接池
	 	 -->
		 <dataSource type="POOLED">
		 <!-- 配置数据库信息  -->
		 <property name="driver" value="com.mysql.jdbc.Driver"/>
		 <property name="url" value="jdbc:mysql://localhost:3306/goodsadmin"/>
		 <property name="username" value="用户名"/>
		 <property name="password" value="密码"/>
		 </dataSource>
	 </environment>
 </environments>
 <mappers>
 	<!-- 加载映射文件 -->
 	<mapper resource="com/johnny/entity/personMapper.xml"/>
 </mappers>
</configuration>

测试类:TestMybatis

package com.johnny.entity;

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;

public class TestMybatis {
	
	public static void selectPersonById() throws IOException {
		//1、加载资源文件:获取mybatis配置文件输入流/MybatisDemo0/src/com/johnny/entity/config.xml
		InputStream in = Resources.getResourceAsStream("config.xml");
		//2、 通过 SqlSessionFactoryBuilder 获得SqlSessionFactory 的实例
		SqlSessionFactory sqlFactory =  new SqlSessionFactoryBuilder().build(in);
		
		//3、获取session对象 --相当于JDBC中的Connection对象
		SqlSession session = sqlFactory.openSession();
		//xml命名空间+sql语句id
		String statement = "com.johnny.personMapper.selectPersonById";
		Person per = session.selectOne(statement,1);
		System.out.println(per);
	}
	
	public static void selectAllPerson() throws IOException {
		InputStream in = Resources.getResourceAsStream("config.xml");
		SqlSessionFactory sqlFactory =  new SqlSessionFactoryBuilder().build(in);
		SqlSession session = sqlFactory.openSession();
		String statement = "com.johnny.personMapper.selectAllPerson";
		List<Person> per = session.selectList(statement);
		System.out.println(per);
	}
	
	public static void addPerson() throws IOException {
		InputStream in = Resources.getResourceAsStream("config.xml");
		SqlSessionFactory sqlFactory =  new SqlSessionFactoryBuilder().build(in);
		
		SqlSession session = sqlFactory.openSession();
		String statement = "com.johnny.personMapper.addPerson";
		
		Person per =  new Person(3, "ls", 55);
		
		int count = session.insert(statement, per);
		//提交事务
		session.commit();
		System.out.println("添加"+ count + "个人");
	}
	
	public static void updatePerson() throws IOException {
		InputStream in = Resources.getResourceAsStream("config.xml");
		SqlSessionFactory sqlFactory =  new SqlSessionFactoryBuilder().build(in);
		
		SqlSession session = sqlFactory.openSession();
		String statement = "com.johnny.personMapper.updatePerson";
		Person per = new Person();
		per.setId(3);		
		per.setAge(36);
		per.setName("lxs");
		
		int count = session.update(statement, per);
		session.commit();
		System.out.println("修改"+ count + "个人");
	}
		
	
	public static void deletePerson() throws IOException {
		InputStream in = Resources.getResourceAsStream("config.xml");
		SqlSessionFactory sqlFactory =  new SqlSessionFactoryBuilder().build(in);
		
		SqlSession session = sqlFactory.openSession();
		String statement = "com.johnny.personMapper.deletePersonById";
		
		int count = session.delete(statement, 3);
		//提交事务
		session.commit();
		
		System.out.println("删除"+ count + "个人");
	}
	

	

	public static void main(String[] args) throws IOException {
		
		selectAllPerson();
//		addPerson();
//		updatePerson();
		deletePerson();
		selectAllPerson();
	
		
		

	}

}

实体类person.java

package com.johnny.entity;

public class Person {
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return this.id+"- "+ this.name+"- " +this.age;
	}
	
	public Person() {}
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	public Person(int id,String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	private int id;
	private String name;
	private int age;
	

}

注意
如果使用事务方式为jdbc,则需要手动commit提交事务,即session.commit();

以上是关于Mybatis 学习笔记—— 基础方式的CRUD的主要内容,如果未能解决你的问题,请参考以下文章

#yyds干货盘点#MyBatis-plus学习笔记

MyBatis第三课 MyBatis映射文件的CRUD操作<方式二>

MyBatis基础学习笔记--摘录

MyBatis-Plus学习——CRUD的使用

MyBatis完成代理方式查询数据以及核心文件配置

Mybatis学习笔记