博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mybatis接口编程方式实现增删改查
阅读量:6716 次
发布时间:2019-06-25

本文共 10579 字,大约阅读时间需要 35 分钟。

前面一章Mybatis入门概述及第一个Mybatis实例实现增删改查 ,已经搭建好了eclipse,mybatis,mysql的环境,并且实现了一个简单的查询。请注意,这种方式是用SqlSession实例来直接执行已映射的SQL语句:

?

1
session.selectOne("com.mucfc.model.EmployeerMapper.findEmployeerByID", 1);
其实还有更简单的方法,而且是更好的方法,使用合理描述参数和SQL语句返回值的接口(比如EmployeerMapper.java),这样现在就可以至此那个更简单,更安全的代码,没有容易发生的字符串文字和转换的错误.下面是详细过程:

本文要改成以接口类来实现增删改查

整个工程目录 :

image

本文示例工程免费下载

1、首先还是mybatis的配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>

br>PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

其中配置文件mysql.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?charset=utf8
username=root
password=christmas258@

2、数据表对应的类Employeer.JAVA

package com.mucfc.model;

import java.io.Serializable;

/**

  • 雇员信息类
    *@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;}@Overridepublic String toString() {    return "Employeer [employeer_id=" + employeer_id + ", employeer_name="            + employeer_name + ", employeer_age=" + employeer_age            + ", employeer_department=" + employeer_department            + ", employeer_worktype=" + employeer_worktype + "]";}

}

然后是SQL语句的配置Employeer.xml:

<?xml version="1.0" encoding="UTF-8" ?>

br>"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

insert into `t_employeer`(employeer_name,employeer_age,employeer_department,employeer_worktype) values(#{employeer_name},#{employeer_age},#{employeer_department},#{employeer_worktype})
delete from `t_employeer` where employeer_id = #{employeer_id}
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}

?
1

注意com.mucfc.mapper.EmployeerMapper这个类是存在的,它是一个接口类,上一讲我们是使用com.mucfc.model.EmployeerMapper,而上一讲的这个类是不存在的

4、SQL语句映射类EmployeerMapper.java

package com.mucfc.mapper;

import com.mucfc.model.Employeer;

/**

  • SQL语句映射类
  • @author linbingwen
  • @time 2015.5.11
    */

public interface EmployeerMapper {

/** * 注意要和Employeer.xml的方法名对应 */public Employeer findEmployeerByID(int id);/** * 注意要和Employeer.xml的方法名对应 */public void addEmployeer(Employeer employeer);/** * 注意要和Employeer.xml的方法名对应 */public void deleteEmployeer(int id);/** * 注意要和Employeer.xml的方法名对应 */public void updateEmployeer(Employeer employeer);

}

5、测试:

(1)增加命令

上一讲Mybatis入门概述及第一个Mybatis实例实现增删改查 中的方式:

/**

  • 增加
    */

public static void addEmployeer(Employeer employeer){

SqlSession session = null;try {    session = sqlSessionFactory.openSession();     //返回值是记录条数      int resultCount = session.insert("com.mucfc.model.EmployeerMapper.addEmployeer", employeer );      System.out.printf("当前插入的employeer_id :%d    当前插入数据库中条数:%d " , employeer.getEmployeer_id() ,resultCount);  //获取插入对象的id      System.out.println("");    session.commit() ;          } finally {    session.close();}

}

改成以接口编程的方式:

/**

  • 增加
    */

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();}

}

(2)删除命令

上一讲【Mybatis】Mybatis入门概述及第一个Mybatis实例实现增删改查 中的方式:

/**

  • 删除
  • */

public static void deleteEmployeer(int id){

SqlSession session = null;try {    session = sqlSessionFactory.openSession();     //返回值是记录条数       int resultCount=session.delete("com.mucfc.model.EmployeerMapper.deleteEmployeer",id);       System.out.println("当前删除数据库中条数: "+resultCount);  //获取插入对象的id      session.commit() ;          } finally {    session.close();}

}

改成以接口编程的方式:

/**

  • 删除
  • */

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();}

}

(3)查找命令

上一讲【Mybatis】Mybatis入门概述及第一个Mybatis实例实现增删改查 中的方式:

/**

  • 查找
    */

public static void findEmployeerById(int id) {

SqlSession session = null;try {    session = sqlSessionFactory.openSession();    Employeer employeer = (Employeer) session.selectOne(            "com.mucfc.model.EmployeerMapper.findEmployeerByID", 1);    if (employeer == null)        System.out.println("null");    else        System.out.println(employeer);} finally {    session.close();}

}

改成以接口编程的方式:

/**

* 查找 */public static void findEmployeerById(int id) {    SqlSession session = null;    try {        session = sqlSessionFactory.openSession();        EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);        Employeer employeer=employeerMapper.findEmployeerByID(id);        if (employeer == null)            System.out.println("null");        else            System.out.println(employeer);    } finally {        session.close();    }}

(4)修改命令

上一讲【Mybatis】Mybatis入门概述及第一个Mybatis实例实现增删改查 中的

/**

  • 更改
    */

public static void updateEmployeer(Employeer employeer){

SqlSession session = null;try {    session = sqlSessionFactory.openSession();     session.update("com.mucfc.model.EmployeerMapper.updateEmployeer",employeer);        session.commit() ;          } finally {    session.close();}

}

改成以接口编程的方式:

/**

  • 更改
    */

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();}

}

这是一个完整的测试:

package com.mucfc.test;

import java.io.IOException;

import java.io.Reader;

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.mucfc.mapper.EmployeerMapper;

import com.mucfc.model.Employeer;

public class MybatisTest {

private static SqlSessionFactory sqlSessionFactory;private static Reader reader;static {    try {        reader = Resources.getResourceAsReader("mybatis-config.xml");        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);    } catch (Exception e) {        e.printStackTrace();    }}/** * 查找 */public static void findEmployeerById(int id) {    SqlSession session = null;    try {        session = sqlSessionFactory.openSession();        EmployeerMapper employeerMapper=session.getMapper(EmployeerMapper.class);        Employeer employeer=employeerMapper.findEmployeerByID(id);        if (employeer == null)            System.out.println("null");        else            System.out.println(employeer);    } finally {        session.close();    }}/** * 增加 */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();    }     }/** * 删除 *  */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();    }}/** * 更改 */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();    }     }public static void main(String[] args) {                                Employeer employeer1=new Employeer();    employeer1.setEmployeer_name("李四");    employeer1.setEmployeer_age(23);    employeer1.setEmployeer_department("产品一部");    employeer1.setEmployeer_worktype("开发工程师");         Employeer employeer2=new Employeer();    employeer2.setEmployeer_name("张三");    employeer2.setEmployeer_age(30);    employeer2.setEmployeer_department("产品二部");    employeer2.setEmployeer_worktype("测试工程师");         Employeer employeer3=new Employeer();    employeer3.setEmployeer_name("小王");    employeer3.setEmployeer_age(22);    employeer3.setEmployeer_department("产品三部");    employeer3.setEmployeer_worktype("数据分析师");              Employeer employeer4=new Employeer();    employeer4.setEmployeer_name("明明");    employeer4.setEmployeer_age(22);    employeer4.setEmployeer_department("财会部");    employeer4.setEmployeer_worktype("财务人员");     //插入    addEmployeer(employeer1);    addEmployeer(employeer2);    addEmployeer(employeer3);    addEmployeer(employeer4);    findEmployeerById(26);    deleteEmployeer(27);         //更改    employeer2.setEmployeer_id(28);    employeer2.setEmployeer_age(21);    employeer2.setEmployeer_department("产品四部");    updateEmployeer(employeer2);}

}

测试结果:

插入了4条数据,ID为25~28

然后27号被删除

29号被修改

image

转载地址:http://leelo.baihongyu.com/

你可能感兴趣的文章
配置sunspot tomcat结合sunspot_rails
查看>>
飞信系统4月29日升级后飞信机器人无法使用的解决办法
查看>>
Canonical今天宣布推出Plex Media Server作为Snap Store中的Snap应用程序
查看>>
Font Awesome
查看>>
Dubbo消费者
查看>>
虚拟化中虚拟机处理器核数与物理主机cpu的关系
查看>>
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type
查看>>
MYSQL: mysqlbinlog读取二进制文件报错read_log_event()
查看>>
随机产生由特殊字符,大小写字母以及数字组成的字符串,且每种字符都至少出现一次...
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
java21:捕鱼达人
查看>>
Zabbix 服务端搭建
查看>>
Java - 一个单例
查看>>
学习JAVA 持续更新
查看>>
Spring propertyConfigurer类
查看>>
Linux系统分析工具之uptime,top(一)
查看>>
EIGRP之DUAL(扩散更新算法)
查看>>
cacti自定义数据收集脚本,创建Data Templates和Graph Templates
查看>>
对你同样重要的非技术贴,一封有效的求职信的具体写法
查看>>