MyBatis对数据库的增删改查操作,简单示例

之前一直实用Hibernate进行开发,最近公司在使用Mybatis,根据网上的示例,做了一个简单的Demo,以便日后复习

总体结构如下图



首先是创建一个工程,然后导入两个jar包,然后编写mybatis的jdbc配置文件Configuration.xml

Configuration.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 alias="User" type="com.demo.bean.User" />
	</typeAliases>

	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
				<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
				<property name="username" value="scott" />
				<property name="password" value="scott" />
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<mapper resource="com/demo/bean/User.xml" />
	</mappers>
</configuration>
User类,文章中省略getter和setter方法

package com.demo.bean;

import java.util.Date;

public class User {
	private String id;
	private String name;
	private String password;
	private Date birthday;
	private String address;

}
然后是创建sql映射文件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.demo.bean.User">
	<!-- 查询所有用户 -->
	<select id="selectAllUsers" resultType="User">
		select * from valid_user
	</select>

	<!-- 根据id查询用户 -->
	<select id="findUserById" resultType="User">
		select * from valid_user where id=#{id}
	</select>

	<!-- 根据id更新用户 -->
	<select id="updateUserById" resultType="User">
		update valid_user set name=#{name},address=#{address} where id=#{id}
	</select>

	<!-- 添加新用户 -->
	<select id="addUser" resultType="User">
		insert into valid_user(id,name,password,address) values(seq_valid_user.nextval,#{name},#{password},#{address})
	</select>

	<!-- 根据id删除用户 -->
	<delete id="deleteUserById">
		delete from valid_user where id=#{id}
	</delete>
</mapper>
然后就是编辑测试类

package com.demo.Test;

import java.io.Reader;
import java.util.List;

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 com.demo.bean.User;

public class TestConnection {
	private static SqlSessionFactory sqlSessionFactory;
	private static Reader reader;

	static {
		try {
			reader = Resources.getResourceAsReader("Configuration.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询所有User对象
	 * @param id
	 */
	public static void selectAllUsers() {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			List<User> listUsers = session.selectList("com.demo.bean.User.selectAllUsers");
			for (User user:listUsers) {
				System.out.println("ID:" + user.getId() + ",姓名:" + user.getName() + ",密码:" + user.getPassword() + ",住址:" + user.getAddress());
			}
		} finally {
			session.close();
		}
	}
	
	/**
	 * 根据id查询User对象
	 * @param id
	 */
	public static void findUserById(String id) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			User user = (User) session.selectOne("com.demo.bean.User.findUserById", id);
			System.out.println("ID:" + user.getId() + ",姓名:" + user.getName() + ",密码:" + user.getPassword() + ",住址:" + user.getAddress());
		} finally {
			session.close();
		}
	}

	/**
	 * 根据id更新User对象
	 * @param id
	 */
	public static void updateUserById(String id,User user) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			session.update("com.demo.bean.User.updateUserById",user);
			session.commit(); 
		} finally {
			session.close();
		}
	}
	
	/**
	 * 添加一条User对象
	 */
	public static void addUser(User user) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			session.insert("com.demo.bean.User.addUser",user);
			session.commit(); 
		} finally {
			session.close();
		}
	}

	/**
	 * 删除一条User对象
	 */
	public static void deleteUserById(String id) {
		SqlSession session = sqlSessionFactory.openSession();
		try {
			session.delete("com.demo.bean.User.deleteUserById",id);
			session.commit(); 
		} finally {
			session.close();
		}
	}
	
	public static void main(String[] args) {
	
		selectAllUsers();
		
//		findUserById("1"); // 根据id查询User对象
		
//		User user=new User();
//		user.setId("2");
//		user.setName("Zams");
//		user.setAddress("河南、郑州");
//		updateUserById("2",user);	// 根据id更新User对象
//		findUserById("2"); 
		
//		User add_user=new User();
//		add_user.setName("古力娜扎");
//		add_user.setPassword("3412312");
//		add_user.setAddress("河南、郑州、开封");
//		addUser(add_user);	// 根据id更新User对象
//		findUserById("5"); 
		
//		deleteUserById("4");
	}
}

运行效果如下;

ID:1,姓名:X-rapido,密码:rapido,住址:北京朝阳、海淀
ID:2,姓名:Zams,密码:gril,住址:河南、郑州
ID:3,姓名:盖尔加朵,密码:3412312,住址:河南、郑州
ID:5,姓名:古力娜扎,密码:3412312,住址:河南、郑州、开封











郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。