ps_zhanglei的专栏

发表工作心得及生活心得的地方

Mybatis简单增删改查操作

MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

首先我们需要下载MyBatis的jar包。Mybatis3.3.0jar包

然后第一步配置通用配置xml:

<span style="font-size:14px;"><?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="oracle.jdbc.driver.OracleDriver" />
				<property name="url" value="jdbc:oracle:thin:@localhost:1521:MYWEBDB" />
				<property name="username" value="WEBUSER" />
				<property name="password" value="123456" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="com/smile/entity/userMapper.xml" />
	</mappers>
</configuration></span>
environments中的jdbc是配置与数据库的链接。mappers是配置匹配的xml配置。

package com.smile.entity;

public class User {
	private int id;
	private String name;
	private int age;
	
	public User(){
		
	}
	
	public User(int id,String name,int age){
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	public int getId() {
		return id;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
}
User中的字段名与数据库表的字段名一致。

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="com.smile.entity.userMapper">
	<select id="getUser" parameterType="int"
		resultType="com.smile.entity.User">
		select * from users where id=#{id}
	</select>
	<insert id="insertUser" parameterType="com.smile.entity.User">
		insert into users(id,name,age) values(#{id},#{name},#{age})
	</insert>
	<delete id="deleteUser" parameterType="int">
		delete from users where id=#{id}
	</delete>
	<update id="updateUser" parameterType="com.smile.entity.User">
		update users set name=#{name},age=#{age} where id=#{id}
	</update>
	<select id="selectUser" parameterType="int" resultType="com.smile.entity.User">
		select * from users where id=#{id}
	</select>
	<select id="selectAllUsers" resultType="com.smile.entity.User">
		select * from users order by id
	</select>
	<select id="selectUserCount" resultType="int">
		select count(*) from users
	</select>
</mapper>

这里我们可以写自己的sql比较方便。

UserServices.java中封装了增删改查的方法:

package com.smile.services;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.smile.entity.User;

public class UserService {
	public void getUser(SqlSession session,int id){
		// 映射sql 的标识字符串
		String statement = "com.smile.entity.userMapper"
						+ ".getUser";
		// 执行查询返回一个唯一user 对象的sql
		User user = session.selectOne(statement, id);
		System.out.println(user);
	}
	
	public void insertUser(SqlSession session,User user){
		// 映射sql 的标识字符串
		String statement = "com.smile.entity.userMapper"
						+ ".insertUser";
		// 执行查询返回一个唯一user 对象的sql
		session.insert(statement, user);
		session.commit();
		System.out.println("UserCount:"+getUserCount(session));
	}
	
	public int getUserCount(SqlSession session){
		// 映射sql 的标识字符串
		String statement = "com.smile.entity.userMapper"
						+ ".selectUserCount";
		// 执行查询返回一个唯一user 对象的sql
		return session.selectOne(statement);
	}
	
	public List<User> getAllUsers(SqlSession session){
		// 映射sql 的标识字符串
		String statement = "com.smile.entity.userMapper"
						+ ".selectAllUsers";
		// 执行查询返回一个唯一user 对象的sql
		return session.selectList(statement);
	}
}
新建一个Test类进行测试:

package com.smile.test;

import java.io.IOException;
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.smile.entity.User;
import com.smile.services.UserService;

public class Test {
	public static void main(String[] args) throws IOException {
		String resource = "Mybatis-Config.xml";
		// 加载mybatis 的配置文件(它也加载关联的映射文件)
		Reader reader = Resources.getResourceAsReader(resource);
		// 构建sqlSession 的工厂
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
				.build(reader);
		SqlSession session = sessionFactory.openSession();
		try{
			// 创建能执行映射文件中sql 的sqlSession
			
			UserService us = new UserService();
			int id = 1;
			us.getUser(session, id);
			
	//		User user = new User(3,"张无忌",20);
	//		us.insertUser(session, user);
			List<User> users = us.getAllUsers(session);
			for(int i = 0;i< users.size();i++){
				System.out.println(users.get(i));
			}
		}finally{
			session.close();
		}
	}
}
整个项目的目录结构如下图:





阅读更多
文章标签: mybatis 持久层框架
个人分类: MyBatis
想对作者说点什么? 我来说一句

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭