Mybatis通过接口的方式实现增删改查

  导入jar包

  【mybatis

  

  oracle

  

  生成数据库

  

  

  1、添加Mybatis的配置文件mybatis-config.xml

  在src目录下创建一个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>
      <properties resource="db.properties"></properties>
      <typeAliases>
          <package name="com.model"/>
      </typeAliases>

      <environments default="development">
          <environment id="development">
              <transactionManager type="JDBC" />
              <dataSource type="POOLED">
                  <property name="username" value="${jdbc.username}"/>
                  <property name="password" value="${jdbc.password}"/>
                  <property name="url" value="${jdbc.url}"/>
                  <property name="driver" value="${jdbc.driverClass}"/>
              </dataSource>

          </environment>
      </environments>

      <mappers>
          <!-- <mapper resource="com/dao/UserMapper.xml"/> -->
          <package name="com.dao"/>
      </mappers>
  </configuration>

  db.properties如下:

jdbc.username=root
jdbc.password=123
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.driverClass=oracle.jdbc.OracleDriver

  2、定义表所对应的实体类,如下图所示:

  

package com.model;
// Generated 2017-4-19 10:19:42 by Hibernate Tools 5.2.0.CR1

import java.math.BigDecimal;

import org.apache.ibatis.type.Alias;

/**
 * TestId generated by hbm2java
 */
public class TestId {

    private BigDecimal id;
    private String username;
    private String password;

    public TestId() {
    }

    public TestId(BigDecimal id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public BigDecimal getId() {
        return this.id;
    }

    public void setId(BigDecimal id) {
        this.id = id;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean equals(Object other) {
        if ((this == other))
            return true;
        if ((other == null))
            return false;
        if (!(other instanceof TestId))
            return false;
        TestId castOther = (TestId) other;

        return ((this.getId() == castOther.getId())
                || (this.getId() != null && castOther.getId() != null && this.getId().equals(castOther.getId())))
                && ((this.getUsername() == castOther.getUsername()) || (this.getUsername() != null
                        && castOther.getUsername() != null && this.getUsername().equals(castOther.getUsername())))
                && ((this.getPassword() == castOther.getPassword()) || (this.getPassword() != null
                        && castOther.getPassword() != null && this.getPassword().equals(castOther.getPassword())));
    }

    public int hashCode() {
        int result = 17;

        result = 37 * result + (getId() == null ? 0 : this.getId().hashCode());
        result = 37 * result + (getUsername() == null ? 0 : this.getUsername().hashCode());
        result = 37 * result + (getPassword() == null ? 0 : this.getPassword().hashCode());
        return result;
    }

    @Override
    public String toString() {
        return "TestId [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

}
package com.model;

import java.util.Date;

public class TestInfo {
    private Integer ids;
    private TestId testId;
    private String address;
    private Date birthday;
    public Integer getIds() {
        return ids;
    }
    public void setIds(Integer ids) {
        this.ids = ids;
    }
    public TestId getTestId() {
        return testId;
    }
    public void setTestId(TestId testId) {
        this.testId = testId;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public TestInfo(Integer ids, TestId testId, String address, Date birthday) {
        super();
        this.ids = ids;
        this.testId = testId;
        this.address = address;
        this.birthday = birthday;
    }
    public TestInfo() {
        super();
    }
    @Override
    public String toString() {
        return "TestInfo [ids=" + ids + ", testId=" + testId + ", address=" + address + ", birthday=" + birthday + "]";
    }

}

   3、定义操作test表的sql映射文件

  

UserInfoMapper.java接口如下:

package com.dao;

import java.util.List;

import com.model.TestInfo;

public interface UserInfoMapper {
    public List<TestInfo> select();
}

UserMapper.java接口如下:

package com.dao;

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

import com.model.TestId;

public interface UserMapper {
    public Integer add(TestId ti);

    public Integer delete(Integer id);

    public Integer update(TestId ti);

    public TestId select(Integer id);

    public List<TestId> selectlist(Map<String, Object> map);
}

UserInfoMapper.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.dao.UserInfoMapper">    <!-- 一对一级连查询方法1 -->
      <resultMap type="testInfo" id="userslist">
          <id property="ids" column="ids"/>

          <result property="testId.id" column="id"/>
          <result property="testId.username" column="username"/>
          <result property="testId.password" column="password"/>

          <result property="address" column="address"/>
          <result property="birthday" column="birthday"/>
      </resultMap>
      <!-- 一对一级连查询方法2 -->
      <resultMap type="testInfo" id="userlist">
          <association property="testId" column="id" select="com.dao.UserMapper.select"></association>
      </resultMap>

      <select id="select" resultMap="userslist">
          select * from testinfo ti left join test t on ti.id=t.id
      </select>
  </mapper>

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.dao.UserMapper">

    <resultMap type="testId" id="users"></resultMap>

    <insert id="add" parameterType="testId">
        insert into test values(sq_mybatis.nextval,#{username},#{password})
    </insert>

    <delete id="delete" parameterType="Integer">
        delete test t where t.id=#{id}
    </delete>

    <update id="update" parameterType="testId">
        update test t set t.username=#{username},t.password=#{password} where t.id=#{id}
    </update>

    <select id="select" parameterType="Integer" resultType="testId">
        select * from test t where t.id=#{id}
    </select>

    <select id="selectlist" parameterType="Map" resultMap="users">
        select * from test t where t.username like #{username} and t.password like #{password}
    </select>
</mapper>

  4、创建一个MybatisUtil的和Junit的类,来进行测试

   

MybatisUtil.java如下:

package com.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * mybatis工具类
 * @author Administrator
 *
 */
public class MybatisUtil {
    private static SqlSessionFactory ssf;
    private static SqlSession ss;

    /**
     * 获取mybatis核心sqlsessionfactory
     * @return
     */
    private static SqlSessionFactory getSqlSessionFctory(){
        InputStream it = null;

        try {
            it = Resources.getResourceAsStream("mybatis-config.xml");
            ssf= new SqlSessionFactoryBuilder().build(it);
            ss=ssf.openSession();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return ssf;
    }
    /**
     * 获取sqlsession
     * @return
     */
    public static SqlSession getSqlSession(){
        ss= getSqlSessionFctory().openSession();
        return ss;

    }
    public static void main(String[] args){
        System.out.println(getSqlSession());
    }
}

Junit.java如下:

package com.util;

import static org.junit.Assert.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.dao.UserMapper;
import com.model.TestId;

public class Junit {

    private SqlSession ss;
    private UserMapper um;

    @Before
    public void setUp() throws Exception {
        ss=MybatisUtil.getSqlSession();
        um=ss.getMapper(UserMapper.class);
    }

    @After
    public void tearDown() throws Exception {
        ss.commit();
        ss.close();
    }

    public void test() {
        TestId ti = new TestId();
        ti.setUsername("张张柳");
        ti.setPassword("443221");
        //int i =ss.insert("com.dao.UserMapper.add",ti);
        int i=um.add(ti);
        System.out.println(i);
    }

    public void test1(){
        int i = um.delete(401);
        System.out.println(i);
    }

    public void test2(){
        TestId ti = new TestId();
        ti.setId(new BigDecimal(441));
        ti.setUsername("张张柳2");
        ti.setPassword("443221");

        um.update(ti);
    }

    public void test3(){
        TestId ti =um.select(441);
        System.out.println(ti);
    }
    @Test
    public void tes4(){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", "张%");
        map.put("password", "%2%");
        List<TestId> list =um.selectlist(map);
        for(TestId ti:list){
            System.out.println(ti);
        }

    }

}

Junit2.java如下:

package com.util;

import static org.junit.Assert.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.dao.UserInfoMapper;
import com.dao.UserMapper;
import com.model.TestId;
import com.model.TestInfo;

public class Junit2 {

    private SqlSession ss;
    private UserInfoMapper um;

    @Before
    public void setUp() throws Exception {
        ss=MybatisUtil.getSqlSession();
        um=ss.getMapper(UserInfoMapper.class);
    }

    @After
    public void tearDown() throws Exception {
        ss.commit();
        ss.close();
    }

    @Test
    public void test() {
        List<TestInfo> list = um.select();
        for(TestInfo ti :list){
            System.out.println(ti);
        }
    }

}
时间: 2024-12-11 07:02:21

Mybatis通过接口的方式实现增删改查的相关文章

【Mybatis】Mybatis接口编程方式实现增删改查

林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 前面一章[Mybatis]Mybatis入门概述及第一个Mybatis实例实现增删改查,已经搭建好了eclipse,mybatis,mysql的环境,并且实现了一个简单的查询.请注意,这种方式是用SqlSession实例来直接执行已映射的SQL语句: session.selectOne("com.mucfc.model.EmployeerMapper.findEmployeerByID&qu

通用DAO之MyBatis封装,封装通用的增删改查(二)

曾经发过一篇文章,大概写的就是阿海多么多么厉害,见到某位同事在Hibernate的基础上封装了一下,就以一己之力开发什么什么框架,最后写了个超大的一坨的事. 那么,后续篇来了.阿海不是自负之人,当之前的CRUD框架并没有达到理想的结果时,阿海转向了Mybatis封装.别问我为什么不是Hibernate.我本来就不喜欢Hibernate,即使在之前的一家公司一直被强制性的约束使用Hibernate时,也没有对Hibernate产生什么真正的好感,反而屡次发现了Hibernate的一些问题. 或许是

Dynamics CRM OData方式进行增删改查时报错的问题

今天在通过OData终结点update记录的时候报"Error processing request stream. The request should be a valid top-level resource object",经过谷歌查询后发现是属性赋值时格式不对,其实从英文的字面意思也能猜出一二,原始代码如下面 var updateEntity = new Object(); updateEntity.sc_bizState = EMEntityState.complete ;

Mybatis学习总结(二)—使用接口实现数据的增删改查

在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num信息.而personMapper则是该实体类的一个配置文件.需要注意的是,在上一篇博文中,namespace属性的值是其本身,而在这一篇中,使用的是接口.那么两者有什么区别呢?使用接口,那么相关的操作方法不用自己去实现,只需要调用该接口的相关的方法就能够实现相应的功能. 那么,在这里就有一个问题,接

通用DAO之MyBatis封装,封装通用的增删改查(三)

曾将发布过俩篇关于Mybatis封装的文章,当时曾曾承诺过当测试没有问题后阿海会整理一下然后将原代码发布出来. 那么今天正好朋友找我要一份那套mybatis封装的源码,我便整理了一份,想想这么长时间了并没有发现什么明显的bug,于是决定将它发出来. 喜欢的朋友可以在这里下载: http://aiyiupload.oss-cn-beijing.aliyuncs.com/blog/img/2016/06/28/15/6d69ad50-ab53-4f4f-b4e7-1fed010bfdb9.rar 关

mybatis映射文件之基本的增删改查

借之前配置好的环境: 1.首先在Employee .java中加上有参的构造器和无参的构造器. 2.采用mapper中的class属性配置映射文件. <mappers> <mapper class="com.gong.mybatis.dao.EmployeeMapper" /> </mappers> 3.EmployeeMapper.java package com.gong.mybatis.dao; import com.gong.mybatis.

Oracle+mybatis实现对数据的简单增删改查

第一步:--创建一个表空间:名字叫 mybatis,建在D盘下的date文件夹下: 第二步:创建用户,名字叫  lisi  ,密码为  :123456 第三步:给用户授权: 第四步:我们在    lisi  用户下创建一个emp表: 随便插入几个值: (这个表在网上有,可以扒下来) 第五步:(这里用的是eclipse)打开eclipse建立一个maven项目,在网上maven仓库中搜索mybatis导包 我们用3.4.6这个: 将这段代码粘在刚才在eclipse中建的项目的pom.xml中<必须

Spring mvc整合mybatis基于mysql数据库实现用户增删改查及其分页显示的完整入门实例【转】

Spring mvc整合mybatis例子, 基于mysql数据库实现对用户的增.删.改.查,及分页显示的完整例子. 查询显示用户 添加用户 更新用户 官方验证: 项目截图 必须修改applicationContext.xml中mysql的配置为本地的,否则启动失败. 另外jar包多一个ehcache.jar无关紧要,删除即可. 1. 使用阿里巴巴Druid连接池(高效.功能强大.可扩展性好的数据库连接池.监控数据库访问性能.支持Common-Logging.Log4j和JdkLog,监控数据库

5、Spring+Struts2+MyBatis+分页(无代理)增删改查

1.创建如下项目结构 2.在src下的com.entity包下创建Dept.java 1 package com.entity; 2 /** 3 * 部门表 4 * @author Holly老师 5 * 6 */ 7 public class Dept { 8 private Integer deptno; //部门编号 9 private String dname; //部门名称 10 private String loc; //位置 11 12 13 public Dept() { 14