`

MyBatis CRUD Operations

    博客分类:
  • ORM
 
阅读更多

1.Maven Dependency

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.fool.mybatis</groupId>
	<artifactId>MyBatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<mybatis-version>3.2.1</mybatis-version>
		<mysql-connector-version>5.1.24</mysql-connector-version>
		<junit-version>4.11</junit-version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis-version}</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql-connector-version}</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit-version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>

 

2.Project Directory


 

3.src/main/resources

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>
	<properties resource="jdbc.properties" />

	<typeAliases>
		<package name="org.fool.mybatis.model" />
	</typeAliases>

	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<!-- Using classpath relative resources -->
		<mapper resource="mapper/UserMapper.xml" />
		<!-- Using mapper interface classes -->
		<mapper class="org.fool.mybatis.mapper.UserMapper" />
	</mappers>
</configuration>

 注意:这里使用UserMapper.xml和UserMapper接口,只是为了说明一下,有两种实现方式,想使用哪种,全看个人喜好。

 

jdbc.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8 
jdbc.username = root
jdbc.password = 123456

 

schema.sql

drop table if exists t_user ;

create table t_user
(
	uid integer not null auto_increment,
	username varchar(20) not null,
	password varchar(20) not null,
	nickname varchar(20) not null,
	email varchar(30) not null,
	constraint user_uid_pk primary key(uid)
);

insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");
insert into t_user(username, password, nickname, email)
values("mybatis", "mybatis", "orm", "mybatis@orm.org");

commit;

 

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="org.fool.mybatis.model.User">

	<insert id="add" parameterType="User">
		insert into t_user(username, password, nickname, email)
			values(#{username}, #{password}, #{nickname}, #{email})
	</insert>
	
	<update id="update" parameterType="User">
		update t_user set password = #{password}, nickname = #{nickname}, email = #{email}
			where uid = #{uid}
	</update>
	
	<delete id="delete" parameterType="int">
		delete from t_user where uid = #{uid}
	</delete>
	
	<select id="load" parameterType="int" resultType="User">
		select * from t_user where uid = #{uid}
	</select>
	
	<select id="list" resultType="User">
		select * from t_user
	</select>
	
	<select id="load_by_username" parameterType="string" resultType="User">
		select * from t_user where username = #{username}
	</select>
</mapper>

 

4.src/main/java

User.java

package org.fool.mybatis.model;

public class User
{
	private int uid;
	private String username;
	private String password;
	private String nickname;
	private String email;

	public int getUid()
	{
		return uid;
	}

	public void setUid(int uid)
	{
		this.uid = uid;
	}

	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 getNickname()
	{
		return nickname;
	}

	public void setNickname(String nickname)
	{
		this.nickname = nickname;
	}

	public String getEmail()
	{
		return email;
	}

	public void setEmail(String email)
	{
		this.email = email;
	}

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

}

 MyBatisUtil.java

package org.fool.mybatis.util;

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

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

public class MyBatisUtil
{
	private static SqlSessionFactory sessionFactory;

	private MyBatisUtil()
	{
	}

	static
	{
		try
		{
			InputStream is = Resources
					.getResourceAsStream("mybatis-config.xml");

			sessionFactory = new SqlSessionFactoryBuilder().build(is);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public static SqlSessionFactory getSqlSessionFactory()
	{
		return sessionFactory;
	}
}

 UserMapper.java

package org.fool.mybatis.mapper;

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 org.fool.mybatis.model.User;

public interface UserMapper
{
	@Insert("insert into t_user(username, password, nickname, email) values(#{username}, #{password}, #{nickname}, #{email})")
	public void add(User user);

	@Update("update t_user set password = #{password}, nickname = #{nickname}, email = #{email} where uid = #{uid}")
	public void update(User user);

	@Delete("delete from t_user where uid = #{uid}")
	public void delete(int id);

	@Select("select * from t_user where uid = #{uid}")
	public User load(int id);

	@Select("select * from t_user")
	public List<User> list();
	
	@Select("select * from t_user where username = #{username}")
	public User loadByUsername(String username);
}

 

5.src/test/java

TestMyBatis.java

package org.fool.mybatis.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.fool.mybatis.model.User;
import org.fool.mybatis.util.MyBatisUtil;
import org.junit.Assert;
import org.junit.Test;

public class TestMyBatis
{

	@Test
	public void testAdd()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = new User();
		user.setUsername("Hibernate");
		user.setPassword("123456");
		user.setNickname("Little Hi");
		user.setEmail("hibernate@orm.org");

		session.insert(User.class.getName() + ".add", user);

		session.commit();

		session.close();
	}

	@Test
	public void testLoad()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = session.selectOne(User.class.getName() + ".load", 11);

		System.out.println(user);

		session.close();
	}

	@Test
	public void testUpdate()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = session.selectOne(User.class.getName() + ".load", 11);
		
		System.out.println(user);

		user.setPassword("mybatis");
		user.setNickname("orm");
		user.setEmail("mybatis@orm.org");
		
		session.update(User.class.getName() + ".update", user);

		session.commit();

		System.out.println(user);

		session.close();
	}

	@Test
	public void testDelete()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = session.selectOne(User.class.getName() + ".load", 11);

		System.out.println(user);

		session.delete(User.class.getName() + ".delete", user);

		session.commit();

		session.close();
	}

	@Test
	public void testList()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		List<User> users = session.selectList(User.class.getName() + ".list",
				null);

		Assert.assertEquals(10, users.size());

		session.close();
	}

	@Test
	public void testLoadByUsername()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = session.selectOne(User.class.getName()
				+ ".load_by_username", "Hibernate");
		
		System.out.println(user);
		
		session.close();
	}
}

 TestMyBatisByMapper.java

package org.fool.mybatis.test;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.fool.mybatis.mapper.UserMapper;
import org.fool.mybatis.model.User;
import org.fool.mybatis.util.MyBatisUtil;
import org.junit.Assert;
import org.junit.Test;

public class TestMyBatisByMapper
{

	@Test
	public void testAdd()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = new User();
		user.setUsername("Hibernate");
		user.setPassword("123456");
		user.setNickname("Little Hi");
		user.setEmail("hibernate@orm.org");

		session.getMapper(UserMapper.class).add(user);

		session.commit();

		session.close();
	}

	@Test
	public void testLoad()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = session.getMapper(UserMapper.class).load(11);

		System.out.println(user);

		session.close();
	}

	@Test
	public void testUpdate()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = session.getMapper(UserMapper.class).load(11);

		System.out.println(user);

		user.setPassword("mybatis");
		user.setNickname("orm");
		user.setEmail("mybatis@orm.org");

		session.getMapper(UserMapper.class).update(user);

		session.commit();

		System.out.println(user);

		session.close();
	}

	@Test
	public void testDelete()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		session.getMapper(UserMapper.class).delete(11);

		session.commit();

		session.close();
	}

	@Test
	public void testList()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		List<User> users = session.getMapper(UserMapper.class).list();

		Assert.assertEquals(10, users.size());

		session.close();
	}

	@Test
	public void testLoadByUsername()
	{
		SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();

		User user = session.getMapper(UserMapper.class).loadByUsername(
				"Hibernate");

		System.out.println(user);

		session.close();
	}
}

 

 6.Best in Practice

创建相应的MyBatisUtil完成对Session的获取

不使用annotation完成sql的映射

 

 

 

 

  • 大小: 18.9 KB
分享到:
评论

相关推荐

    ibatis mybatis crud 完整代码

    在IT行业中,`iBatis` 和 `MyBatis` 是两种非常流行的持久层框架,它们主要用于简化Java应用程序中的数据库操作。本篇文章将深入探讨这两个框架,并基于`CRUD`(Create, Read, Update, Delete)操作来阐述如何使用它们...

    mybatisCRUD (Mybatis 增删改查 代码)

    本项目主要展示了如何使用Mybatis进行基本的CRUD(创建、读取、更新、删除)操作,并且结合了Junit进行单元测试,确保代码的正确性。 在Mybatis中,CRUD操作的核心在于Mapper接口和XML配置文件。Mapper接口定义了...

    05实现mybatis简单crud功能demo

    05实现mybatis简单crud功能demo05实现mybatis简单crud功能demo05实现mybatis简单crud功能demo05实现mybatis简单crud功能demo05实现mybatis简单crud功能demo05实现mybatis简单crud功能demo05实现mybatis简单crud功能...

    MyBatisCRUD:MyBatis的CRUD操作

    MyBatis CRUD操作Java,MyBatis,单元测试,MySql,Maven的CRUD操作这包含构建和运行MyBatisCRUD应用程序所需的一组指令。建设项目。先决条件设置了JDK 1.6.x或更高版本的Maven 2或更高版本的java_home和m2_home。...

    SpringBoot+MybatisCRUD 整合案例

    这个"SpringBoot+MybatisCRUD 整合案例"是为初学者设计的,旨在帮助他们快速掌握这两个流行的框架的结合使用。 首先,我们需要在项目中引入Spring Boot和MyBatis的依赖。在`pom.xml`文件中,我们需要添加以下Maven...

    ibatis mybatis 分页 crud 完整代码

    本资源"ibatis mybatis 分页 crud 完整代码"包含了这两个框架在CRUD(创建、读取、更新、删除)操作以及分页功能上的实现,下面将详细介绍相关知识点。 1. **Ibatis**: Ibatis 是一款轻量级的Java ORM(对象关系...

    springmvc + mybatis crud demo

    在给定的项目"springmvc + mybatis crud demo"中,可能包含以下内容: 1. **spring.sql**:这是初始化MySQL数据库的脚本,可能包含了创建表和插入示例数据的SQL语句。 2. **springmvc1**:这可能是Spring MVC的配置...

    Mybatis通用DAO设计封装(mybatis)

    这个接口通常会包含CRUD(Create, Read, Update, Delete)的基本方法,如`insert`, `update`, `delete`, `selectById`, `selectAll`等。这些方法可以通过Mybatis的注解或XML配置来绑定SQL语句。 2. **动态SQL**: ...

    2024最新MyBatis CRUD操作,动态SQL HM

    ### 2024最新MyBatis CRUD操作与动态SQL详解 #### 一、MyBatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集...

    第一个mybatis程序——CRUD

    在本教程中,我们将一起探索如何创建并运行你的第一个MyBatis程序,实现CRUD(Create, Read, Update, Delete)操作。这些基本操作是数据库管理的核心,对于任何应用程序来说都是必不可少的。 首先,我们需要理解...

    MyBatis 采用注解方式实现CRUD

    然而,随着Java注解的普及,MyBatis也引入了注解方式来简化配置,让CRUD(创建、读取、更新、删除)操作更加便捷。下面我们将详细介绍如何使用注解实现MyBatis的CRUD。 1. **注解简介** MyBatis 的注解主要包括 `@...

    mybatis CRUD

    本篇文章将深入探讨MyBatis的CRUD(创建、读取、更新、删除)操作,以及相关的核心概念和技术点。 **1. MyBatis 概述** MyBatis 是一个基于Java的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取...

    【自虐1.2】Srping+MyBatis完成CRUD

    【自虐1.2】Spring+MyBatis完成CRUD 在本文中,我们将深入探讨如何结合Spring框架和MyBatis轻量级持久层框架来实现数据库的基本操作,包括创建(Create)、读取(Read)、更新(Update)和删除(Delete),简称为...

    mybatis基础CRUD

    本教程将围绕"Mybatis基础CRUD"这一主题,深入探讨MyBatis如何实现增删改查的基本操作。 首先,我们需要了解MyBatis的基本架构。MyBatis的核心组件包括SqlSessionFactory、SqlSession和Mapper接口。...

    mybatis中使用接口编程方式实现CRUD模板

    本文将深入探讨如何在MyBatis中利用接口实现CRUD(创建、读取、更新、删除)模板。 首先,让我们了解MyBatis的核心概念。MyBatis是一个优秀的持久层框架,它允许开发者通过SQL映射文件或者注解来定义SQL语句,避免...

    使用mybatis实现CRUD

    标题 "使用mybatis实现CRUD" 涉及到的是在Java开发中使用MyBatis框架进行基本的数据操作,即创建(Create)、读取(Read)、更新(Update)和删除(Delete)。MyBatis是一个优秀的持久层框架,它支持定制化SQL、存储...

    LayUI+Mybatis实现CRUD效果.rar

    利用LayUI+MyBatis实现CRUD操作MySQL数据库 https://blog.csdn.net/qq_29001539/article/details/105613480 雁去雁归雁不散2020-04-19 14:49:17 LayUI+MyBatis实现CRUD操作 项目描述 前端页面采用Layui进行搭建,...

    MyBatis-CRUD

    MyBatis-CRUD 是一个围绕MyBatis框架展开的主题,它主要涵盖了数据库的基本操作,包括创建(Create)、读取(Read)、更新(Update)和删除(Delete)等CRUD操作。MyBatis是一个优秀的持久层框架,它支持定制化SQL、...

    springboot+mybatis实现增删改查(视频+源码)

    springboot+mybatis+postman+crud(视频+源码) https://pan.baidu.com/s/1qYcFDow https://blog.csdn.net/linzhiqiang0316/article/details/78310884?locationNum=3&fps=1

Global site tag (gtag.js) - Google Analytics