MyBatis框架的使用

1.导入Maven包
mybatis 3.2.8版
junit 4.12版
mysql 5.1.37版
dbcp 1.4版
springmvc数据库已创建里创建user表

2.resources下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/springmvc"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="mapping/userMapper.xml"/>
  </mappers>
</configuration>

3.resources下mapping文件下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.tedu.mybatis.dao.IUserDao">
  <insert id="insertUser" parameterType="cn.tedu.mybatis.bean.User" useGeneratedKeys="true" keyProperty="id">
    insert into user(id,username,password,salary) values(null,#{username},#{password},#{salary})
  </insert>
  
  <!-- Mybatis 会自动的将查询结果列名与User的Bean属性对应赋值,如果表的列名与User Bean属性 列名不一致,
  则需要使用列的别名方式修改查询结果列名,使其与User Bean属性一致。 -->
  <select id="findAllUsers" resultType="cn.tedu.mybatis.bean.User">
  	select id,username,password,salary from user
  </select>
  
  <update id="updateUser" parameterType="cn.tedu.mybatis.bean.User">
  	update user set username=#{username},password=#{password},salary=#{salary} where id=#{id}
  </update>
  
  <select id="findUserById" resultType="cn.tedu.mybatis.bean.User" parameterType="int">
  	select id,username,password,salary from user where id=#{id}
  </select>
  
  <delete id="deleteUserById" parameterType="int">
  	delete from user where id=#{id}
  </delete>
  
  <select id="findUsersByParam" resultType="cn.tedu.mybatis.bean.User">
  	select id,username,password,salary from user where username like #{name} and salary >= #{salary}
  </select>
  
  <select id="findUsersByMap" resultType="map">
  	select id,username as name from user
  </select>
  
  <select id="findUsers" resultType="cn.tedu.mybatis.bean.User">
  	select id,username,password,salary from user where ${where} #{param}
  </select>
</mapper>

4.Java Bean类

package cn.tedu.mybatis.bean;

public class User {
	private Integer id;
	private String username;
	private String password;
	private Integer salary;
	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 Integer getSalary() {
		return salary;
	}
	public void setSalary(Integer salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", salary=" + salary + "]";
	}
	
}

5.接口类

package cn.tedu.mybatis.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

import cn.tedu.mybatis.bean.User;

public interface IUserDao {
	/**
	 * 将user数据保存到数据库中,返回更新的个数
	 * @param user 用户信息数据
	 * @return 数据库更新的行数
	 */
	public Integer insertUser(User user);
	
	/**
	 * 查询全部的用户信息
	 */
	public List<User> findAllUsers();
	
	/**
	 * IUserDao 中添加更新方法,将用户信息进行更新
	 * @param user 需要更新的用户信息
	 * @return 更新的行数
	 */
	public Integer updateUser(User user);
		
	public User findUserById(Integer id);
	
	public Integer deleteUserById(Integer id);
	
	/**
	 * MyBatis中多参数查询 要使用注解 @Param 绑定参数名
	 * 在SQL中,要使用参数名来绑定参数 #{salary}
	 * @param salary
	 * @param name
	 * @return
	 */
	public List<User> findUsersByParam(@Param("salary") Integer salary,@Param("name") String name);
		
	/**
	 * 用Map封装查询结果
	 * @return
	 */
	public List<Map<String, Object>> findUsersByMap();
	
	/**
	 * 动态拼接SQL
	 */
	public List<User> findUsers(@Param("where") String where,@Param("param") Object param);
		
}

6.测试类

package cn.tedu.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 org.junit.Before;
import org.junit.Test;

import cn.tedu.mybatis.bean.User;
import cn.tedu.mybatis.dao.IUserDao;

public class DaoTestCase {
	SqlSessionFactory factory;
	
	@Before
	public void init() throws IOException {
		/**
		 * 初始化 SqlSessionFactory
		 */
		String config="config.xml";
		//从classpath中读取配置文件config.xml为输入流
		InputStream in = Resources.getResourceAsStream(config);
		factory = new SqlSessionFactoryBuilder().build(in);
	}
	
	@Test
	public void testInsertUser() {
		/**
		 * 测试利用Mybatis向数据库中插入数据
		 */
		//打开Session
		SqlSession session = factory.openSession();
		//利用 Session 自动创建 IUserDao的实例
		IUserDao dao=session.getMapper(IUserDao.class);
		System.out.println(dao.getClass());
		User user=new User();
		user.setUsername("Tom");
		user.setPassword("123");
		user.setSalary(500); 
		Integer n = dao.insertUser(user);
		System.out.println(n); 
		session.commit();//提交事务
		session.close();
	}
	
	@Test
	public void testInsert() {
		/**
		 * 利用SqlSession直接执行SQL,不访问DAO接口
		 * 与访问dao接口的结果完全一样。
		 * SqlSession提供了两种执行SQL功能
		 */
		SqlSession session = factory.openSession();
		//session.insert("SQL ID",参数对象)
		User user = new User();
		user.setUsername("rose");
		user.setPassword("123");
		user.setSalary(200); 
		Integer n = session.insert("insertUser",user);
		System.out.println(user);
		System.out.println(n); 
		session.commit();//提交事务
		session.close();
	}
	
	@Test
	public void testFindAllUsers() {
		/**
		 * 查询全部用户信息
		 */
		SqlSession session = factory.openSession();
		IUserDao dao=session.getMapper(IUserDao.class);
		List<User> list = dao.findAllUsers();
		for (User user : list) {
			System.out.println(user);
		}
		session.close();
	}
	@Test
	public void testUpdateUser() {
		/**
		 * 测试更新用户信息方法
		 * 1.查询出用户信息
		 * 2.更改用户信息
		 */
		SqlSession session = factory.openSession();
		IUserDao dao=session.getMapper(IUserDao.class);
		User user = dao.findUserById(10);
		System.out.println(user);
		user.setUsername("范XX");
		int n = dao.updateUser(user);
		System.out.println(n);
		session.commit();//提交事务
		session.close();
	}
	@Test
	public void testDeleteUserById() {
		/**
		 * 测试删除用户的方法
		 */
		SqlSession session = factory.openSession();
		IUserDao dao=session.getMapper(IUserDao.class);
		int id = 2;
		int n = dao.deleteUserById(id);
		System.out.println(n); 
		session.commit();//提交事务
		session.close();
	}
	@Test
	public void testFindUsersByParam() {
		/**
		 * 测试多参数查询
		 */
		String name = "%a%";
		Integer salary = 200;
		SqlSession session = factory.openSession();
		IUserDao dao=session.getMapper(IUserDao.class);
		List<User> list = dao.findUsersByParam(salary, name);
		for (User user : list) {
			System.out.println(user);
		}
		session.close();
	}
	@Test
	public void testFindUsersByParam2() {
		String name = "%a%";
		Integer salary = 200;
		SqlSession session = factory.openSession();
		//将多个参数打包到map中传递到selectList方法
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("name",name);
		params.put("salary", salary);
		List<User> list = session.selectList("findUsersByParam",params);
		for (User user : list) {
			System.out.println(user);
		}
		session.close();
	}
	
	@Test
	public void testFindByMap() {
		/**
		 * 测试: 利用map封装查询结果
		 */
		SqlSession session = factory.openSession();
		IUserDao dao=session.getMapper(IUserDao.class);
		List<Map<String, Object>> list = dao.findUsersByMap();
		for(Map<String, Object> map : list) {
			System.out.println(map);
		}
		session.close();
	}
	
	@Test
	public void testFindUsers() {
		String where = "username like";
		Object param = "%a%";
		SqlSession session = factory.openSession();
		IUserDao dao = session.getMapper(IUserDao.class);
		List<User> list = dao.findUsers(where, param);
		for(User user : list) {
			System.out.println(user);
		}
		session.close();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

linsa_pursuer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值