【Mybatis】基于注解实现增删查改和多参数列表查询

林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

【Mybatis】Mybatis入门概述及第一个Mybatis实例实现增删改查【Mybatis】Mybatis接口编程方式实现增删改查演示了如何使用XML来操作Mybatis实现CRUD,但是大量的XML配置文件的编写是非常烦人的。因此Mybatis也提供了基于注解的配置方式,下面我们来演示一下使用接口加注解来实现CRUD的的例子。

一、创建数据库、数据表

use test;
create table t_employeer(
employeer_id int not null  primary key AUTO_INCREMENT ,
employeer_name varchar(50) default null,
employeer_age int default null,
employeer_department varchar(100) default null,
employeer_worktype varchar(100) default null
) 

二、创建工程

整个工程目录如下:

记得要导入相应的包!

1、雇员对应的类Employeer.java

package com.mucfc.model;
/**
 * 雇员信息类
 *@author linbingwen
 *@time 2015.5.11
 */
public class Employeer {
	private Integer employeer_id;
	private String employeer_name;
	private Integer employeer_age ;
	private String employeer_department;
	private String employeer_worktype;

	public Employeer() {
		super();
	}
	public Integer getEmployeer_id() {
		return employeer_id;
	}
	public void setEmployeer_id(Integer employeer_id) {
		this.employeer_id = employeer_id;
	}
	public String getEmployeer_name() {
		return employeer_name;
	}
	public void setEmployeer_name(String employeer_name) {
		this.employeer_name = employeer_name;
	}
	public Integer getEmployeer_age() {
		return employeer_age;
	}
	public void setEmployeer_age(Integer employeer_age) {
		this.employeer_age = employeer_age;
	}
	public String getEmployeer_department() {
		return employeer_department;
	}
	public void setEmployeer_department(String employeer_department) {
		this.employeer_department = employeer_department;
	}
	public String getEmployeer_worktype() {
		return employeer_worktype;
	}
	public void setEmployeer_worktype(String employeer_worktype) {
		this.employeer_worktype = employeer_worktype;
	}
	@Override
	public String toString() {
		return "Employeer [employeer_id=" + employeer_id + ", employeer_name="
				+ employeer_name + ", employeer_age=" + employeer_age
				+ ", employeer_department=" + employeer_department
				+ ", employeer_worktype=" + employeer_worktype + "]";
	}

}

Employeer.xml文件,用来放置一些映射,删除了Sql语句了

<?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.mucfc.dao.EmployeerMapper">

 <!-- 定义数据库字段与实体对象的映射关系 -->
 <resultMap type="Employeer" id="employeerResultMap">
    <id property="employeer_id" column="employeer_id"/>
    <result property="employeer_name" column="employeer_name"/>
    <result property="employeer_age" column="employeer_age"/>
    <result property="employeer_department" column="employeer_department"/>
    <result property="employeer_worktype" column="employeer_worktype"/>
 </resultMap>

 </mapper>

2、配置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>
	<!-- 设置别名  -->
	<typeAliases>
		<typeAlias alias="Employeer" type="com.mucfc.model.Employeer"/>
	</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:3306/test?characterEncoding=UTF-8"/>
			<property name="username" value="root"/>
			<property name="password" value="[email protected]"/>
			</dataSource>
		</environment>
	</environments>

	<!-- 列出映射文件 -->
	<mappers>
		<mapper resource="com/mucfc/model/Employeer.xml" />
	</mappers>
</configuration>

3、EmployeerMapper.java在添加Sql映射语句,使用注解的方式来实现

package com.mucfc.dao;

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

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;

import com.mucfc.model.Employeer;

/**
 * SQL语句映射类
 * @author linbingwen
 * @time 2015.5.11
 */
public interface EmployeerMapper {
    @Select("select * from `t_employeer` where employeer_name like #{employeer_name}")
	@ResultMap("employeerResultMap")
	public List<Employeer> findEmployeerByName(String employeer_name);    

    @Select("select* from `t_employeer` where employeer_name=#{0} and employeer_department=#{1}")
	@ResultMap("employeerResultMap")

	public List<Employeer> findEmployeerByNameandDep(String employeer_name,String employeer_department);
	@ResultMap("employeerResultMap")
	@Select("select* from `t_employeer` where employeer_name=#{key1} and employeer_department=#{key2}")
	public List<Employeer> findEmployeerByNameandDep1(Map<String,String> map);

	@Select("select* from `t_employeer` where employeer_id =#{id}")
	@ResultMap("employeerResultMap")
	public Employeer findEmployeerByID(int id);

     @Insert(" insert into `t_employeer`(employeer_name,employeer_age,employeer_department,employeer_worktype) values(#{employeer_name},#{employeer_age},#{employeer_department},#{employeer_worktype})")
	public void addEmployeer(Employeer employeer);

    @Delete("delete from `t_employeer` where employeer_id = #{employeer_id}")
	public void deleteEmployeer(int id);

    @Update(" update t_employeer set employeer_name = #{employeer_name},employeer_age= #{employeer_age},employeer_department = #{employeer_department} ,employeer_worktype=#{employeer_worktype}  where employeer_id = #{employeer_id}  ")
	public void updateEmployeer(Employeer employeer);

}

4、测试使用

(1)单参数查找

	/**
	 * 查找
	 */
	public static Employeer findEmployeerById(int id) {
		SqlSession session = null;
		Employeer employeer=null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeer=employeerMapper.findEmployeerByID(id);
		} finally {
			session.close();
		}
		return employeer;
	}

对应SQL语句:

	@Select("select* from `t_employeer` where employeer_id =#{id}")
	@ResultMap("employeerResultMap")
	public Employeer findEmployeerByID(int id);

调用:

	  System.out.println(findEmployeerById(10));
	  System.out.println(findEmployeerById(11));

结果:

(2)  添加

	/**
	 * 增加
	 */
	public static void addEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.addEmployeer(employeer);
            session.commit() ;
		} finally {
			session.close();
		}

	}

对应SQL语句:

     @Insert(" insert into `t_employeer`(employeer_name,employeer_age,employeer_department,employeer_worktype) values(#{employeer_name},#{employeer_age},#{employeer_department},#{employeer_worktype})")
	public void addEmployeer(Employeer employeer);

(3)更改

	/**
	 * 更改
	 */
	public static void updateEmployeer(Employeer employeer){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.updateEmployeer(employeer);
            session.commit() ;
		} finally {
			session.close();
		}

	}

对应SQL语句:

    @Update(" update t_employeer set employeer_name = #{employeer_name},employeer_age= #{employeer_age},employeer_department = #{employeer_department} ,employeer_worktype=#{employeer_worktype}  where employeer_id = #{employeer_id}  ")
	public void updateEmployeer(Employeer employeer);

(4)删除

	/**
	 * 删除
	 *
	 */
	public static void deleteEmployeer(int id){
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			employeerMapper.deleteEmployeer(id);
            session.commit() ;
		} finally {
			session.close();
		}
	}

对应SQL语句:

    @Delete("delete from `t_employeer` where employeer_id = #{employeer_id}")
	public void deleteEmployeer(int id);

(5)列表查询

/**
	 * 单参数查询列表
	 */
	public static List<Employeer> getEmployeerList(String employeer_name){
		SqlSession session = null;
		 List<Employeer> employeers=null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			 employeers = employeerMapper.findEmployeerByName(employeer_name);
            session.commit() ;
		} finally {
			session.close();
		}
		return employeers;

    }
	/**
	 * 多参数查询列表
	 */
	public static List<Employeer> getEmployeerList(String employeer_name,String employeer_department){
		SqlSession session = null;
		 List<Employeer> employeers=null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			 employeers = employeerMapper.findEmployeerByNameandDep(employeer_name, employeer_department);
            session.commit() ;
		} finally {
			session.close();
		}
		return employeers;

    }
	/**
	 * 多参数查询列表,使用map
	 */
	public static List<Employeer> getEmployeerList(Map<String, String> map){
		SqlSession session = null;
		 List<Employeer> employeers=null;
		try {
			session = sqlSessionFactory.openSession();
			EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);
			 employeers = employeerMapper.findEmployeerByNameandDep1(map);
            session.commit() ;
		} finally {
			session.close();
		}
		return employeers;

    }

对应的Sql语句

    @Select("select * from `t_employeer` where employeer_name like #{employeer_name}")
	@ResultMap("employeerResultMap")
	public List<Employeer> findEmployeerByName(String employeer_name);    

    @Select("select* from `t_employeer` where employeer_name=#{0} and employeer_department=#{1}")
	@ResultMap("employeerResultMap")
	public List<Employeer> findEmployeerByNameandDep(String employeer_name,String employeer_department);
	@ResultMap("employeerResultMap")
	@Select("select* from `t_employeer` where employeer_name=#{key1} and employeer_department=#{key2}")
	public List<Employeer> findEmployeerByNameandDep1(Map<String,String> map);

	@Select("select* from `t_employeer` where employeer_id =#{id}")
	@ResultMap("employeerResultMap")
	public Employeer findEmployeerByID(int id);

测试:

	System.out.println("=========================使用单参数查询===========================");
		List<Employeer> employeers=getEmployeerList("张三");
		 for(Employeer employeer:employeers){
             System.out.println(employeer);
         }
	 System.out.println("=========================使用多单参数查询===========================");
		 List<Employeer> employeers1=getEmployeerList("张三","产品二部");
		 for(Employeer employeer1:employeers1){
             System.out.println(employeer1);
         }
		 System.out.println("=========================使用多单参数map方式查询===========================");
		 Map<String, String> map = new HashMap<String, String>();
		 map.put("key1", "明明");
		 map.put("key2", "财会部");
		 List<Employeer> employeers2=getEmployeerList(map);
		 for(Employeer employeer2:employeers2){
             System.out.println(employeer2);
         }

结果:

林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

时间: 2024-10-09 06:44:52

【Mybatis】基于注解实现增删查改和多参数列表查询的相关文章

mybatis实现简单的增删查改

接触一个新技术,首先去了解它的一些基本概念,这项技术用在什么方面的.这样学习起来,方向性也会更强一些.我对于mybatis的理解是,它是一个封装了JDBC的java框架.所能实现的功能是对数据库进行增删查改的功能. 首先,需要搭建一个demo,用于学习这个框架的使用方式.(1)在IDE上建立自己的工程目录,一个普通的java工程项目就好,我电脑本地的IDE是Myeclipse.(2)引入搭建框架需要的jar包,这个直接去网上搜索就好.(3)框架的核心实现都是基于配置的,引入jar包后,先配置my

基于MVC实现增删查改

1.首先要理解MVC的架构.新建一个web项目取名叫Service. 2.建立eneity(实体包),tools(连接数据库),DAO(借助result的代码实现增删查改)servlet(实现跳转). 3.在建立实体时一定要和数据库中的字段名一致,否则在运行时会出错.连接数据库时一定要注意数据库名和密码. 4.在DAO层中实现增删查改的语句,并测试,代码如下: public class userDAO {  public List getAllUser(){//查询 String SQL="se

myBatis 实现用户表增删查改操作&lt;方法1 没有使用接口的&gt;(最终版)

在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文件,就去拿到names

myBatis 实现用户表增删查改操作&lt;方法2 加入接口&gt;(最终版)

这2种方法的区别:1.添加接口 2.运用接口来实现 其他的都一样 添加接口 //接口的名字和xml的名字一样,这样xml中的namespace就不用改 public interface UserMapper { //接口名的方法名一定要和xml中的id名一样 public int count(); public void add(User user); public void update(User user); public void delete(User user); public Lis

SpringMVC+Mybatis架构下的增删查改

第一步新建一个Controller,以产品信息为例(ProductController) package com.xcy.ctrl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.anno

MyBatis基于注解----增删改查

select sysdate from dual; --账户表 --账户编号,账户卡号,账户密码,账户余额,账户状态,创建时间 drop table account; create table account ( id number(10) primary key, account_number varchar2(50) not null, account_pwd varchar2(10) not null, account_money number(10,2) not null, accoun

mybatis实现的对数据的增删查改

mybatis实现的对数据的增删查改 前期准备 新建java工程或java wweb工程, 需要导入以下的包, 基本工作已经完成,接下来开始进入正题. 新建实体类 新建与数据库表对应的实体类 package com.edu.hpu.domain; /** * @author Administrator *user表所对应的实体类 */ public class User { //实体类的属性和表的字段名称一一对应 private int id; private String name; priv

MyBatis笔记----Mybatis3.4.2与spring4整合:增删查改

结构图 刚之前没什么区别,多了一个applicationContext.xml 包图 由于之前出了一点错误,有些包可能多加上了 数据库图 model User.java package com.ij34.model; public class User { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.

mybatis从入门到精通(二) 增删查改

mybatis从入门到精通(二) 增删查改 一丶前言 "增删查改"是后台开发的常用操作, 因此, 学习mybatis或者其他orm框架有必要统一学习一下"增删查改". 二丶准备开发环境 使用"mybatis从入门到精通(一) 入门"准备的开发环境 三丶查 -- <select/> UserMapper.java User selectUser(@Param("userId") int userId); UserMa