MyBatis研习录(03)——基于DAO的增删改查操作


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

Android多分辨率适配框架

JavaWeb核心技术系列教程

HTML5前端开发实战系列教程

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

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

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

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


版权声明

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

在本节教程中,我们利用MyBatis的DAO方式实现对数据的增删改查操作。

数据准备

创建数据库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工程,结构如下:
在这里插入图片描述
实现思路:

  • 1、UserDao中定义数据库操作
  • 2、在UserDaoImpl中调用UserMapper.xml中编写的数据库操作语句进行增删改查
  • 3、在MybatisTest中利用JUnit测试UserDaoImpl的各方法。

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 + "]";
	}
	
}

UserDao

package cn.com.dao;

import java.util.List;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public interface UserDao {
	
	public int insertUser(User user);
	
	public int deleteUserById(Integer id);
	
	public int updateUser(User user);
	
	public User queryUserById(Integer id);
	
	public List<User> queryAllUser();
	
}

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.pojo.User">	
  <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="queryAllUser" 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>

要点概述:

  • 1、select标签、insert标签、delete标签、update标签分别用于执行查询、插入、删除、更新。
  • 2、parameterType表示输入参数(传入参数)的类型
  • 3、resultType属性用于指定执行SQL语句之后每行记录对应的javaBean对象的全类名(类型)

参数说明:

<delete id="deleteUserById" parameterType="java.lang.Integer">
     delete from user where id=#{id}
</delete>

在该语句中#{id}是个占位符,即在实际调用过程传入的参数会替代此处的id

<update id="updateUser" parameterType="cn.com.pojo.User">
     update user set username=#{username},password=#{password},gender=#{gender} where id=#{id}
</update>

在该语句中,在实际调用该update时将传入的cn.com.pojo.User类型的对象的username、password、gender属性的值分别赋值给占位符#{username}、#{password}、#{gender}

 <insert id="insertUser" parameterType="cn.com.pojo.User">
     insert into user(username,password,gender) values (#{username},#{password},#{gender})
</insert>

在该语句中,在实际调用该insert时将传入的cn.com.pojo.User类型的对象的username、password、gender属性的值分别赋值给占位符#{username}、#{password}、#{gender}

UserDaoImpl

package cn.com.dao.impl;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import cn.com.dao.UserDao;
import cn.com.pojo.User;
/**
 * 本文作者:谷哥的小弟 
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
public class UserDaoImpl implements UserDao {
	
	private SqlSessionFactory sqlSessionFactory;
	
	public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory=sqlSessionFactory;
	}
	
	@Override
	public User queryUserById(Integer id) {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			//SqlSession.selectOne()查询单条数据
			User user = sqlSession.selectOne("cn.com.pojo.User.queryUserById", id);
			return user;
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			//关闭SqlSession
			sqlSession.close();
		}
		return null;
	}

	@Override
	public List<User> queryAllUser() {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			//SqlSession.selectList()查询多条数据
			List<User> userList = sqlSession.selectList("cn.com.pojo.User.queryAllUser");
			return userList;
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			//关闭SqlSession
			sqlSession.close();
		}
		return null;
	}
	
	@Override
	public int deleteUserById(Integer id) {
		int result=-1;
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			//SqlSession.delete()删除数据
			result=sqlSession.delete("cn.com.pojo.User.deleteUserById", id);
			//SqlSession.commit提交事务
			sqlSession.commit();
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			//关闭SqlSession
			sqlSession.close();
		}
		return result;
	}

	@Override
	public int updateUser(User user) {
		int result=-1;
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			//SqlSession.update()更新数据
			result=sqlSession.update("cn.com.pojo.User.updateUser", user);
			//SqlSession.commit提交事务
			sqlSession.commit();
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			//关闭SqlSession
			sqlSession.close();
		}
		return result;
	}
	
	@Override
	public int insertUser(User user) {
		int result=-1;
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			//SqlSession.update()更新数据
			result=sqlSession.insert("cn.com.pojo.User.insertUser", user);
			//SqlSession.commit提交事务
			sqlSession.commit();
			return result;
		} catch (Exception e) {
			// TODO: handle exception
		}finally {
			//关闭SqlSession
			sqlSession.close();
		}
		return result;
	}

}

要点概述:

  • 1、UserDaoImpl中各方法使用同一个SqlSessionFactory即构造函数中的SqlSessionFactory。
  • 2、使用SqlSession执行增加,删除,更新后需调用commit( )进行提交。
  • 3、使用SqlSession后应调用close( )将其关闭。

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 org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import cn.com.dao.UserDao;
import cn.com.dao.impl.UserDaoImpl;
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() {
		UserDao userDao = new UserDaoImpl(getSqlSessionFactory());
		User user = userDao.queryUserById(1);
		System.out.println(user);
	}

	@Test
	public void testQueryAllUser() {
		UserDao userDao = new UserDaoImpl(getSqlSessionFactory());
		List<User> userList = userDao.queryAllUser();
		Iterator<User> iterator = userList.iterator();
		while (iterator.hasNext()) {
			User user = iterator.next();
			System.out.println(user);
		}
	}

	@Test
	public void testDeleteUserById() {
		UserDao userDao = new UserDaoImpl(getSqlSessionFactory());
		int result = userDao.deleteUserById(1);
		System.out.println("result=" + result);
	}

	@Test
	public void testUpdateUser() {
		UserDao userDao = new UserDaoImpl(getSqlSessionFactory());
		User user = new User(2, "klkl", "123543", "male");
		int result = userDao.updateUser(user);
		System.out.println("result=" + result);
	}

	@Test
	public void testInsertUser() {
		UserDao userDao = new UserDaoImpl(getSqlSessionFactory());
		User user = new User(null, "gugu", "123456", "female");
		int result = userDao.insertUser(user);
		System.out.println("result=" + result);
		System.out.println(user);
	}

}

要点概述:

  • 1、MybatisTest中对各方法采用Junit测试。
  • 2、MybatisTest中使用单例模式确保各方法使用同一个SqlSessionFactory对象,避免重复创建。

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官方博客

分享到微信朋友圈

×

扫一扫,手机浏览