欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis实现数据的增删改查实例(CRUD)

程序员文章站 2024-02-21 15:43:10
什么是 mybatis? mybatis 是支持普通 sql 查询,存储过程和高级映射的优秀持久层框架。 mybatis 消除了几乎所有的 jdbc 代码和参数的手工设置...

什么是 mybatis?

mybatis 是支持普通 sql 查询,存储过程和高级映射的优秀持久层框架。 mybatis 消除了几乎所有的 jdbc 代码和参数的手工设置以及对结果集的检索。mybatis 可以使用简单的xml 或注解用于配置和原始映射,将接口和 java 的 pojo(plain old java objects,普通的java对象)映射成数据库中的记录。

mybatis下载:

mybatis实例

对一个user表的crud操作:

user表:

-- ----------------------------
-- table structure for `user`
-- ----------------------------
drop table if exists `user`;
create table `user` (
 `id` int(11) not null auto_increment,
 `username` varchar(50) default null,
 `userage` int(11) default null,
 `useraddress` varchar(200) default null,
 primary key (`id`)
) engine=innodb auto_increment=6 default charset=utf8;

-- ----------------------------
-- records of user
-- ----------------------------
insert into `user` values ('1', 'summer', '30', 'shanghai');
insert into `user` values ('2', 'test2', '22', 'suzhou');
insert into `user` values ('3', 'test1', '29', 'some place');
insert into `user` values ('4', 'lu', '28', 'some place');
insert into `user` values ('5', 'xiaoxun', '27', 'nanjing');

在src目录下建一个mybatis的xml配置文件configuration.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>
  <!-- mybatis别名定义 -->
  <typealiases> 
    <typealias alias="user" type="com.mybatis.test.user"/> 
  </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://127.0.0.1:3306/mybatis" />
      <property name="username" value="root"/>
      <property name="password" value="admin"/>
      </datasource>
    </environment>
  </environments>
  
  <!-- mybatis的mapper文件,每个xml配置文件对应一个接口 -->
  <mappers>
    <mapper resource="com/mybatis/test/user.xml"/>
  </mappers>
</configuration>

定义user mappers的user.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.mybatis.test.iuseroperation">

  <!-- select语句 -->
  <select id="selectuserbyid" parametertype="int" resulttype="user">
    select * from `user` where user.id = #{id}
  </select>
  
  <!-- 定义的resultmap,可以解决类的属性名和数据库列名不一致的问题-->
  <!-- <resultmap type="user" id="userresultmap">
    <id property="id" column="user_id" />
    <result property="username" column="user_username" />
    <result property="userage" column="user_userage" />
    <result property="useraddress" column="user_useraddress" />
  </resultmap> -->
  
  <!-- 返回list的select语句,注意 resultmap的值是指向前面定义好的 -->
  <!-- <select id="selectusersbyname" parametertype="string" resultmap="userresultmap">
    select * from user where user.username = #{username}
  </select> -->
  
  <select id="selectusersbyname" parametertype="string" resulttype="user">
    select * from user where user.username = #{username}
  </select>
  
  <!--执行增加操作的sql语句。id和parametertype分别与iuseroperation接口中的adduser方法的名字和参数类型一致。
  usegeneratedkeys设置为"true"表明要mybatis获取由数据库自动生成的主键;keyproperty="id"指定把获取到的主键值注入到user的id属性--> 
  <insert id="adduser" parametertype="user" 
    usegeneratedkeys="true" keyproperty="id"> 
    insert into user(username,userage,useraddress) 
       values(#{username},#{userage},#{useraddress}) 
  </insert>
  
  <update id="updateuser" parametertype="user" >
    update user set username=#{username},userage=#{userage},useraddress=#{useraddress} where id=#{id}
  </update>
  
  <delete id="deleteuser" parametertype="int">
    delete from user where id=#{id}
  </delete>
  
</mapper>

配置文件实现了接口和sql语句的映射关系。selectusersbyname采用了2种方式实现,注释掉的也是一种实现,采用resultmap可以把属性和数据库列名映射关系定义好,property为类的属性,column是表的列名,也可以是表列名的别名!

user类的定义:

package com.mybatis.test;

public class user {
  
  private int id;
  private string username;
  private int userage;
  private string useraddress;
  
  public int getid() {
    return id;
  }
  
  public void setid(int id) {
    this.id = id;
  }
  
  public string getusername() {
    return username;
  }
  
  public void setusername(string username) {
    this.username = username;
  }
  
  public int getuserage() {
    return userage;
  }
  
  public void setuserage(int userage) {
    this.userage = userage;
  }
  
  public string getuseraddress() {
    return useraddress;
  }
  
  public void setuseraddress(string useraddress) {
    this.useraddress = useraddress;
  }
  
  @override
  public string tostring(){
    return this.username+" "+this.userage+" "+this.useraddress;
  }

}

iuseroperaton定义:

package com.mybatis.test;

import java.util.list;

public interface iuseroperation {
  
  public user selectuserbyid(int id);
  
  public list<user> selectusersbyname(string username);
  
  public void adduser(user user);
  
  public void updateuser(user user);
  
  public void deleteuser(int id);
  
}

iuseroperation为操作接口,函数名和mybatis的xml配置文件中的操作id名对应。

测试类test:

package com.mybatis.test;

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;

public class test {

  private static sqlsessionfactory sqlsessionfactory;
  private static reader reader;

  static {
    try {
      reader = resources.getresourceasreader("configuration.xml");
      sqlsessionfactory = new sqlsessionfactorybuilder().build(reader);
    } catch (exception e) {
      e.printstacktrace();
    }
  }

  public static sqlsessionfactory getsession() {
    return sqlsessionfactory;
  }

  public void getuserbyid(int userid) {
    sqlsession session = sqlsessionfactory.opensession();
    try {
      iuseroperation useroperation = session
          .getmapper(iuseroperation.class);
      user user = useroperation.selectuserbyid(userid);
      if (user != null) {
        system.out.println(user.getid() + ":" + user.getusername()
            + ":" + user.getuseraddress());
      }

    } finally {
      session.close();
    }
  }

  public void getuserlist(string username) {
    sqlsession session = sqlsessionfactory.opensession();
    try {
      iuseroperation useroperation = session
          .getmapper(iuseroperation.class);
      list<user> users = useroperation.selectusersbyname(username);
      for (user user : users) {
        system.out.println(user.getid() + ":" + user.getusername()
            + ":" + user.getuseraddress());
      }

    } finally {
      session.close();
    }
  }

  /**
   * 增加后要commit
   */
  public void adduser() {
    user user = new user();
    user.setuseraddress("place");
    user.setusername("test_add");
    user.setuserage(30);
    sqlsession session = sqlsessionfactory.opensession();
    try {
      iuseroperation useroperation = session
          .getmapper(iuseroperation.class);
      useroperation.adduser(user);
      session.commit();
      system.out.println("新增用户id:" + user.getid());
    } finally {
      session.close();
    }
  }

  /**
   * 修改后要commit
   */
  public void updateuser() {
    sqlsession session = sqlsessionfactory.opensession();
    try {
      iuseroperation useroperation = session
          .getmapper(iuseroperation.class);
      user user = useroperation.selectuserbyid(1);
      if (user != null) {
        user.setuseraddress("a new place");
        useroperation.updateuser(user);
        session.commit();
      }
    } finally {
      session.close();
    }
  }

  /**
   * 删除后要commit.
   * 
   * @param id
   */
  public void deleteuser(int id) {
    sqlsession session = sqlsessionfactory.opensession();
    try {
      iuseroperation useroperation = session
          .getmapper(iuseroperation.class);
      useroperation.deleteuser(id);
      session.commit();
    } finally {
      session.close();
    }
  }

  public static void main(string[] args) {
    try {
      test test = new test();
      // test.getuserbyid(1);
      // test.getuserlist("test1");
      // test.adduser();
      // test.updateuser();
      // test.deleteuser(6);

    } catch (exception e) {
      system.out.println(e.getmessage());
    }
  }

}

代码下载:mybaitssimpledemo_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。