mybatis在CRUD

一. 一个简短的引论:

Mybatis本是apache的一个开源项目ibatis, 2010年这个项目由apache software foundation迁移到了google code, 而且改名为Mybatis.

Mybatis是一个基于Java的持久层框架.

二. 增删改查:

1. 代码结构图:

2. User实体类:

/**
 * User实体类
 */
public class User {

	private String id;
	private String uname; // 注意: 该字段名称与数据库字段不一致
	private String address;

	@Override
	public String toString() {
		return "{id: " + id + ", uname: " + uname + ", address: " + address + "}";
	}

}

// 省略getter和setter方法

3. 实体映射文件: User.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.zdp.domain.User">

	<!-- 数据库字段与实体字段相应 -->
	<resultMap type="User" id="userBean">
		<id column="id" property="id"/>
		<result column="username" property="uname"/>
		<result column="address" property="address"/>
	</resultMap>

	<!-- 查: 查询全部User -->
	<select id="selectAllUsers" resultMap="userBean">
		select id, username, address from user
	</select>

	<!-- 查: 依据id查询User, 返回值为userBean -->
	<!-- id:当前sql语句的唯一标识, parameterType:參数类型, resultType:返回值类型 -->
	<select id="selectUserById" parameterType="string" resultMap="userBean">
		select * from user where id = #{userid}
	</select>

	<!-- 查: 依据id查询User, 返回值为HashMap -->
	<select id="selectUserByIdForMap" parameterType="string" resultType="hashmap">
		select id, username, address from user where id = #{userid}
	</select>

	<!-- 增: 插入User, 參数为userBean(调用getter方法获取參数值) -->
	<insert id="insertUser" parameterType="User">
		insert into user(id, username, address) values (#{id}, #{uname}, #{address});
	</insert>

	<!-- 增: 插入User, 參数为hashmap(调用userMap.get(key)获取參数) -->
	<insert id="insertUserForMap" parameterType="hashmap">
		insert into user(id, username, address) values (#{id}, #{uname}, #{address});
	</insert>

	<!-- 删: 依据id删除User, 參数为userId -->
	<delete id="deleteUserById" parameterType="string">
		delete from user where id = #{userid}
	</delete>

	<!-- 改: 依据id更新User, 參数为userBean(调用getter方法获取參数值) -->
	<update id="updateUserById" parameterType="User">
		update user set username = #{uname}, address = #{address} where id = #{id}
	</update>

	<!-- 改: 依据id更新User, 參数为map(调用userMap.get(key)获取參数) -->
	<update id="updateUserByIdForMap" parameterType="hashmap">
		update user set username = #{uname}, address = #{address} where id = #{id}
	</update>

	<!-- 查: 动态sql: 使用 "where 1=1" -->
	<select id="selectUserByCondition1" parameterType="User" resultMap="userBean">
		select id, username, address from user where 1=1
		<if test="id != null">
			and id = #{id}
		</if>
		<!-- uname指的是实体的属性 -->
		<if test="uname != null">
			and username = #{uname}
		</if>
		<if test="address != null">
			and address = #{address}
		</if>
	</select>

	<!-- 查: 动态sql: 使用where标签 -->
	<select id="selectUserByCondition2" parameterType="User" resultMap="userBean">
		select id, username, address from user
		<where>
			<if test="id != null">
			    id = #{id}
			</if>
			<!-- uname指的是实体的属性 -->
			<if test="uname != null">
				and username = #{uname}
			</if>
			<if test="address != null">
				and address = #{address}
			</if>
		</where>
	</select>

</mapper>

4. 全局配置文件: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>
	<typeAliases>
		<typeAlias type="com.zdp.domain.User" alias="User" />
	</typeAliases>
	<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/test" />
				<property name="username" value="root" />
				<property name="password" value="root" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<!-- 映射文件的位置 -->
		<mapper resource="com/zdp/domain/User.xml" />
	</mappers>
</configuration>

typeAliases: 为java类型指定别名, 能够再xml文件里用别名替代java类的全限定名.

5. sql文件:

CREATE DATABASE test;  

USE test;  

CREATE TABLE USER(
  id VARCHAR(36) PRIMARY KEY,
  username VARCHAR(64),
  address VARCHAR(128)
)  

INSERT INTO USER (id, username, address) VALUES("001", "zhangsan", "Wuhan");
INSERT INTO USER (id, username, address) VALUES("002", "lisi", "Shanghai");   

6. log4j

log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

7. 測试文件:

/**
 * 測试mybatis - user增删改查
 */
public class UserTest {

	private SqlSessionFactory ssf; 

	@Before
	public void initSF() throws Exception {
		String resource = "sqlMapConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		ssf = new SqlSessionFactoryBuilder().build(inputStream);
	}

	// 查询全部User
	@Test
	public void testSelectAllUsers() throws Exception {
		SqlSession session = ssf.openSession();
		List<User> users = session.selectList("com.zdp.domain.User.selectAllUsers");
		for (User user : users) {
			System.out.println(user);
		}
	}

	// 依据id查询User, 返回值为userBean
	@Test
	public void testSelectUserById() throws Exception {
		SqlSession session = ssf.openSession();
		User user = session.selectOne("com.zdp.domain.User.selectUserById", "001");
		System.out.println(user);
	}

	// 依据id查询User, 返回值为HashMap
	@Test
	public void testSelectUserByIdForMap() throws Exception {
		SqlSession session = ssf.openSession();
		Map<String, Object> userMap = session.selectOne("com.zdp.domain.User.selectUserByIdForMap", "001");
		System.out.println(userMap);
	}

	// 插入User, 參数为userBean
	@Test
	public void testInsertUser() throws Exception {
		SqlSession session = ssf.openSession();

		// 构建实体
		User user = new User();
		user.setId("003");
		user.setUname("wangwu");
		user.setAddress("beijing");

		int i = session.insert("com.zdp.domain.User.insertUser", user);
		// 提交事务
		session.commit();
	}

	// 插入User, 參数为hashmap
	@Test
	public void testInsertUserForMap() throws Exception {
		SqlSession session = ssf.openSession();
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("id", "004");
		userMap.put("uname", "zhaoliu");
		userMap.put("address", "tianjin");

		int i = session.insert("com.zdp.domain.User.insertUserForMap", userMap);
		session.commit();
	}

	// 依据id删除User, 參数为userId
	@Test
	public void testDeleteUserById() throws Exception {
		SqlSession session = ssf.openSession();
		int i = session.delete("com.zdp.domain.User.deleteUserById", "004");
		session.commit();
	}

	// 依据id更新User, 參数为userBean
	@Test
	public void testUpdateUserById() throws Exception {
		SqlSession session = ssf.openSession();

		User user = new User();
		user.setId("001");
		user.setUname("zhangsanf");
		user.setAddress("wuhan");

		int i = session.update("com.zdp.domain.User.updateUserById", user);
		session.commit();
	}

	// 依据id更新User, 參数为hashMap
	@Test
	public void testUpdateUserByIdForMap() throws Exception {
		SqlSession session = ssf.openSession();
		Map<String, Object> userMap = new HashMap<String, Object>();

		userMap.put("id", "001");
		userMap.put("uname","zhangsan");
		userMap.put("address", "beijing");

		int i = session.update("com.zdp.domain.User.updateUserByIdForMap", userMap);
		session.commit();
	}

	// 动态条件查询:
	@Test
	public void testSelectUserByCondition() throws Exception {
		SqlSession session = ssf.openSession();

		User user = new User();
		user.setUname("lisi");
		List<User> users = session.selectList("com.zdp.domain.User.selectUserByCondition1", user);
		// List<User> users = session.selectList("com.zdp.domain.User.selectUserByCondition2", user);

		for (User u : users) {
			System.out.println(u);
		}
	}
}

SqlSessionFactory是一个创建SqlSession的工厂类, 通过SqlSession实例, 开发人员可以直接进行业务逻辑的操作, 二不须要反复编写JDBC相关的模板代码.

版权声明:本文博主原创文章,博客,未经同意不得转载。

时间: 2024-10-29 19:10:50

mybatis在CRUD的相关文章

MyBATIS使用CRUD

MyEclipse不提供自动生成,这里提供mybatis文件包和开发文档 http://download.csdn.net/detail/u010026901/7489319 自己建立配置文件, <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http

【MyBatis】MyBatis实现CRUD操作

1.实现基本CRUD功能 使用MyBatis对数据完整的操作,也就是CRUD功能的实现.根据之前的内容,要想实现CRUD,只需要进行映射文件的配置. 范例:修改EmpMapper.xml文件,实现CRUD <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http:/

尚硅谷-MyBatis的CRUD操作

项目结构: User实体类代码: package com.atguigu.mybatis.bean; public class User { private int id; private String name; private int age; public User() { super(); } public User(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = ag

MyBatis Tutorial – CRUD Operations and Mapping Relationships – Part 1---- reference

http://www.javacodegeeks.com/2012/11/mybatis-tutorial-crud-operations-and-mapping-relationships-part-1.html CRUD OperationsMyBatis is an SQL Mapper tool which greatly simplifies the database programing when compared to using JDBC directly. Step1: Cre

mybatis 通用CRUD的替换方法

http://git.oschina.net/alexgaoyh/MutiModule-parent 代码此次变更较大,使用了mybatis-generator-maven-plugin 插件,把之前多模块项目中的domain部分删除,将这一部分代码整合到persise部分,原因是使用mybatis-generator-maven-plugin插件的时候,能够自动生成实体类,减少代码移动相关的工作量. 前一段时间使用maven多模块项目整合了spring mybatis部分,最近在处理通用CRU

mybatis实现CRUD操作和优化代码及调试(mysql数据库)(三)

继续(二)说 1.工程结构 2.新建db.properties文件(我的数据库没有设置密码) driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis name=root password= 3.log4j.jar加入工程并添加log4j.xml文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:conf

spirngmvc整合mybatis实现CRUD

一.建立一张简单的User表 CREATE TABLE `users` ( `id` int(20) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL, `age` int(20) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8; -- ------------------------------ Records o

Spring boot 入门三:spring boot 整合mybatis 实现CRUD操作

开发环境延续上一节的开发环境这里不再做介绍 添加mybatis依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> DAO层接口(这里是直接通过注解实现数据库操作,不

基于MyBatis的CRUD操作

一.基于XML实现1.定义SQL映射XML文件studentMapper.xml:<mapper namespace="com.mapping.studentMapper">    <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getStudent,id属性值必须是唯一的,不能够重复    使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型    resultType=&