MyBatis研习录(04)——基于Mapper接口的增删改查操作


C语言自学完备手册(33篇)

Android多分辨率适配框架

JavaWeb核心技术系列教程

HTML5前端开发实战系列教程

MySQL数据库实操教程(35篇图文版)

推翻自己和过往——自定义View系列教程(10篇)

走出思维困境,踏上精进之路——Android开发进阶精华录

讲给Android程序员看的前端系列教程(40集免费视频教程+源码)


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

概述

在本节教程中,我们利用MyBatis的Mapper接口方式实现对数据的增删改查操作。那么什么是Mapper接口呢?其实,它就是以前的DAO只不过其命名规范为xxxMapper,例如:UserMapper。

使用Mapper接口实现增删改查等数据库操作时不需要编写接口的实现类,但是必须遵守以下的开发规范:

  • 1、Mapper.xml配置文件中的命名空间namespace的值必须是Mapper接口的全类名
  • 2、Mapper.xml配置文件中的id值必须对应于Mapper接口中的方法名
  • 3、Mapper.xml配置文件中的parameterType参数类型必须和Mapper接口中的方法的输入参数类型一致
  • 4、Mapper.xml配置文件中的resultType返回值类型必须和Mapper接口中的方法的返回值类型一致

数据准备

创建数据库mybatisDatabase和表user

DROP DATABASE IF EXISTS mybatisDatabase;
CREATE DATABASE mybatisDatabase;
use mybatisDatabase;
CREATE TABLE user(
  id INT primary key auto_increment,
  username VARCHAR(50),
  password VARCHAR(50),
  gender VARCHAR(10)
);

INSERT INTO user(username,password,gender) VALUES("lucy","123456","female");
INSERT INTO user(username,password,gender) VALUES("momo","234567","female");
INSERT INTO user(username,password,gender) VALUES("xixi","345678","female");
INSERT INTO user(username,password,gender) VALUES("pepe","456123","female");

SELECT * FROM user;

搭建开发环境

创建普通的Java工程,结构如下:
在这里插入图片描述

User

package cn.com.pojo;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class User {
	private Integer id;
	private String username;
	private String password;
	private String gender;
	public User() {
		
	}

	public User(Integer id, String username, String password, String gender) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.gender = gender;
	}

	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 getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", gender=" + gender + "]";
	}
	
}

UserMapper

package cn.com.mapper;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.MapKey;

import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public interface UserMapper {
	
	public int insertUser(User user);
	
	public int deleteUserById(Integer id);
	
	public int updateUser(User user);
	
	public User queryUserById(Integer id);
	
	public List<User> queryAllUserList();
	
	@MapKey("id")
	public Map<Integer,User> queryAllUserMap();
	
}

UserMapper.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="cn.com.mapper.UserMapper">	
  <select id="queryUserById" parameterType="java.lang.Integer" resultType="cn.com.pojo.User">
    select id,username,password,gender from user where id = #{id}
  </select>
  
  <select id="queryAllUserList" resultType="cn.com.pojo.User">
     select id,username,password,gender from user
  </select>
  
  <select id="queryAllUserMap" resultType="cn.com.pojo.User">
     select id,username,password,gender from user
  </select>
  
  <delete id="deleteUserById" parameterType="java.lang.Integer">
     delete from user where id=#{id}
  </delete>
  
  <update id="updateUser" parameterType="cn.com.pojo.User">
     update user set username=#{username},password=#{password},gender=#{gender} where id=#{id}
  </update>
  
  <!--  插入User至数据库
  <insert id="insertUser" parameterType="cn.com.pojo.User">
     insert into user(username,password,gender) values (#{username},#{password},#{gender})
  </insert>
  -->
  
  <!-- 插入User至数据库并返回表自动生成的主键(方式一)
  <insert id="insertUser" parameterType="cn.com.pojo.User" useGeneratedKeys="true" keyProperty="id">
     insert into user(username,password,gender) values (#{username},#{password},#{gender})
  </insert>
   -->
  
  <!-- 插入User至数据库并返回表自动生成的主键(方式二) -->
  <insert id="insertUser" parameterType="cn.com.pojo.User">
     <selectKey order="AFTER" keyProperty="id" resultType="int">
		select last_insert_id()
	</selectKey>
     insert into user(username,password,gender) values (#{username},#{password},#{gender})
  </insert>
  
</mapper>

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/mybatisDatabase"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- 配置mapper -->
  <mappers>
    <mapper resource="cn/com/pojo/UserMapper.xml"/>
  </mappers>
  
</configuration>

MybatisTest

package cn.com.test;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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 cn.com.mapper.UserMapper;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class MybatisTest {

	static SqlSessionFactory sqlSessionFactory = null;

	public static SqlSessionFactory getSqlSessionFactory() {
		try {
			if (sqlSessionFactory == null) {
				InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
				SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
				sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
			}
			return sqlSessionFactory;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {

		}
		return null;
	}

	@Test
	public void testQueryUserById() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		User user = userMapper.queryUserById(1);
		System.out.println(user);
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryUserByIdNoMapperInterface() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		User user=sqlSession.selectOne("cn.com.mapper.UserMapper.queryUserById",1);
		System.out.println(user);
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testQueryAllUserList() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		List<User> userList = userMapper.queryAllUserList();
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryAllUserNoMapperInterface() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession执行数据操作
		List<User> userList = sqlSession.selectList("cn.com.mapper.UserMapper.queryAllUser");
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryAllUserMap() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		Map<Integer, User> map=userMapper.queryAllUserMap();
		Set<Integer> keySet = map.keySet();
		Iterator<Integer> iterator = keySet.iterator();
		while(iterator.hasNext()) {
			 Integer key = iterator.next();
			 User user = map.get(key);
			 System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testQueryAllUserMapNoMapperInterface() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		Map<Integer, User> map = sqlSession.selectMap("cn.com.mapper.UserMapper.queryAllUserMap", "id");
		Set<Integer> keySet = map.keySet();
		Iterator<Integer> iterator = keySet.iterator();
		while(iterator.hasNext()) {
			 Integer key = iterator.next();
			 User user = map.get(key);
			 System.out.println(user);
		}
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testDeleteUserById() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		//利用SqlSession执行数据操作
		int result = userMapper.deleteUserById(1);
		System.out.println("result=" + result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testDeleteUserByIdNoMapperInterface() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession执行数据操作
		int result =sqlSession.delete("cn.com.mapper.UserMapper.deleteUserById",1);
		System.out.println("result=" + result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testUpdateUser() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User(2, "klkl", "123543", "male");
		//利用SqlSession执行数据操作
		int result = userMapper.updateUser(user);
		System.out.println("result=" + result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testUpdateUserNoMapperInterface() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		User user = new User(2, "klkl", "123543", "male");
		//利用SqlSession执行数据操作
		int result = sqlSession.update("cn.com.mapper.UserMapper.updateUser", user);
		System.out.println("result=" + result);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}

	@Test
	public void testInsertUser() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		//利用SqlSession得到UserMapper
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = new User(null, "gugu", "123456", "female");
		//利用SqlSession执行数据操作
		int result = userMapper.insertUser(user);
		System.out.println("result=" + result);
		System.out.println(user);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}
	
	@Test
	public void testInsertUserNoMapperInterface() {
		//获取SqlSession
		SqlSession sqlSession=getSqlSessionFactory().openSession();
		User user = new User(null, "gugu", "123456", "female");
		//利用SqlSession执行数据操作
		int result = sqlSession.insert("cn.com.mapper.UserMapper.insertUser",user);
		System.out.println("result=" + result);
		System.out.println(user);
		//提交
		sqlSession.commit();
		//关闭SqlSession
		sqlSession.close();
	}

}

在该示例中使用了两种方式实现增删改查:

  • 1、SqlSessionFactory获取SqlSession,SqlSession获取xxxMapper.java接口,再由xxxMapper.java接口实现数据操作
  • 2、SqlSessionFactory获取SqlSession,再由SqlSession实现数据操作

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
发布了1019 篇原创文章 · 获赞 1913 · 访问量 233万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览