欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis(一),使用三种方式实现对数据库表的增删改查

程序员文章站 2022-05-06 20:57:46
...

    MyBatis实现对数据库表的增删改查主要有三种方式,分别为“基于配置文件方式”、“基于接口方式”和“基于注解方式”,下面主要介绍一下这三种方式是如何实现的。推荐使用接口方式。

(一)基于配置文件方式

涉及三个文件:核心配置文件,映射文件和测试类。核心配置文件主要是配置与数据库相关的信息和注册映射文件;映射文件中涉及SQL语句;测试类是SQL真正执行的地方。

1.核心配置文件SqlMapConfig.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"></transactionManager>
			<!-- 配置数据源 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
				<property name="username" value="root"/>
				<property name="password" value="123"/>
			</dataSource>
		</environment>
	</environments>
	<!-- 注册映射文件 -->
	<mappers>
		<mapper resource="mapper/BlogMapper1.xml"/>
	</mappers>
</configuration>

2.映射文件BlogMapper1.xml,放置于mapper包下

<?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="BlogMapper">
	<!-- 查询 -->
	<select id="selectOne" parameterType="int" resultType="entity.Blog">
		select * from blog where id = #{id}
	</select>
	
	<!-- 插入 --> 
	<insert id="insert" parameterType="entity.Blog">
		INSERT INTO blog(id,title,author_id) VALUES(#{id},#{title},#{author_id})
	</insert>
	
	<!-- 删除 -->
	<delete id="delete" parameterType="int">
		delete from blog where id = #{id}
	</delete>
	
	<!-- 更新 -->
	<update id="update" parameterType="entity.Blog">
		update blog set title = #{title} where id = #{id}
	</update>
</mapper>

3.测试类test1.java

package test;

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

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

import com.mysql.jdbc.Blob;

import entity.Blog;

/**
 * 通过配置文件实现对blog表的增删改查
 * @author baka
 *
 */
public class test1 {

	public static void main(String[] args) {
		//1.获取配置文件名
		String resource = "SqlMapConfig.xml";
		
		//2.得到数据源
		InputStream is = test1.class.getClassLoader().getResourceAsStream(resource);
		
		//3.提供连接,建立工厂
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		
		//4.得到真正的连接
		SqlSession session = factory.openSession();
		
		//5.执行SQL语句
		
		//查询
		String statement = "BlogMapper.selectOne";
		Blog blog = session.selectOne(statement, 2);
		System.out.println(blog);
		
		//插入
		String statement2 = "BlogMapper.insert";
		Blog blog2 = new Blog(8, "wawa", 1);
		session.insert(statement2, blog2);
		
		//修改
		String statement3 = "BlogMapper.update";
		Blog blog3 = new Blog(8, "wawahh", 2);
		session.update(statement3, blog3);
		
		//删除
		String statement4 = "BlogMapper.delete";
		session.update(statement4, 8);
		
		//6、提交事务,关闭连接
		session.commit();
		session.close();
	}
}

(二)基于接口方式,涉及四个文件,核心配置文件、映射文件、测试类和接口类

1.核心配置文件

<mapper resource="mapper/BlogMapper2.xml"/>

2.接口类BlogDao2.java

package dao;

import java.util.List;

import entity.Blog;

public interface BlogDao2 {
	public Blog selectOne(int id);
	public int insert(Blog blog);
	public int delete(int id);
	public int update(Blog blog);
}

3.映射文件BlogMapper2.xml,使用的是上面的映射文件,但有两点需要注意

(1)命名空间必须是接口所在的位置

<mapper namespace="dao.BlogDao2">

我的接口类是“BlogDao.java”,位于"dao"包下

(2)命名空间中的id必须和接口中的方法同名

(3)完整代码

<?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="dao.BlogDao2">
	<!-- 查询 -->
	<select id="selectOne" parameterType="int" resultType="entity.Blog">
		select * from blog where id = #{id}
	</select>
	
	<!-- 插入 --> 
	<insert id="insert" parameterType="entity.Blog">
		INSERT INTO blog(id,title,author_id) VALUES(#{id},#{title},#{author_id})
	</insert>
	
	<!-- 删除 -->
	<delete id="delete" parameterType="int">
		delete from blog where id = #{id}
	</delete>
	
	<!-- 更新 -->
	<update id="update" parameterType="entity.Blog">
		update blog set title = #{title} where id = #{id}
	</update>
</mapper>

4.测试类test2.java

package test;

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

import javax.naming.spi.ObjectFactory;

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

import dao.BlogDao2;
import entity.Blog;

/**
 * 基于接口方式实现blog表的增删改查
 * @author baka
 *
 */
public class test2 {
	public static void main(String[] args) {
		//1.获得配置文件名
		String resource = "SqlMapConfig.xml";
		
		//2.获得数据流
		InputStream is = test2.class.getClassLoader().getResourceAsStream(resource);
		
		//3.提供连接,建立工厂
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
		
		//4.获得真正的连接
		SqlSession session = factory.openSession();
		
		//5.实例化接口
		BlogDao2 blogDao = session.getMapper(BlogDao2.class);
		
		//6.执行SQL语句
		
		//查询
		Blog blog = blogDao.selectOne(2);
		System.out.println(blog);
		
		//插入
		Blog blog2 = new Blog(9, "xxx", 4);
		blogDao.insert(blog2);
		
		//修改
		Blog blog3 = new Blog(9, "xxxL", 4);
		blogDao.update(blog3);
		
		//删除
		blogDao.delete(9);
		
		//7.提交事务,关闭连接
		session.commit();
		session.close();
	}
}

(三)基于注解方式

涉及三个文件,核心配置文件,接口类和测试类,没有映射文件,SQL语句注解写在接口方法中

1.核心配置文件

<mapper class="dao.BlogDao3"/>

2.接口类BlogDao3.java

package dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import entity.Blog;

/**
 * 注解方式
 * @author baka
 *
 */

public interface BlogDao3 {
	@Select("select * from blog where id = #{id}")
	public Blog selectOne(int id);
	
	@Insert("INSERT INTO blog(id,title,author_id) VALUES(#{id},#{title},#{author_id})")
	public int insert(Blog blog);
	
	@Delete("delete from blog where id = #{id}")
	public int delete(int id);
	
	@Update("update blog set title = #{title} where id = #{id}")
	public int update(Blog blog);
}

3.测试类test3.java

package test;

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

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

import dao.BlogDao2;
import dao.BlogDao3;
import entity.Blog;

/**
 * 基于注解方式实现对blog表的增删改查
 * 
 * @author baka
 *
 */
public class test3 {

	public static void main(String[] args) throws IOException {
		// 1.获得配置文件名
		String resource = "SqlMapConfig.xml";

		// 2.获得数据流
		InputStream is = test3.class.getClassLoader().getResourceAsStream(resource);

		// 3.提供连接,建立工厂
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);

		// 4.获得真正的连接
		SqlSession session = factory.openSession();

		// 5.实例化接口
		BlogDao3 blogDao = session.getMapper(BlogDao3.class);

		// 6.执行SQL语句
		
		//查询
		Blog blog = blogDao.selectOne(1);
		System.out.println(blog);
		
		//增加
		Blog blog1 = new Blog(9, "xxx", 4);
		blogDao.insert(blog1);
		
		//修改
		Blog blog3 = new Blog(9, "xxxL", 4);
		blogDao.update(blog3);
		
		//删除
		blogDao.delete(9);
		
		// 7.提交事务,关闭连接
		session.commit();
		session.close();
	}

}