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

mybatis使用xml进行增删改查代码解析

程序员文章站 2023-11-21 14:30:40
mybatis是支持普通sql查询、存储过程和高级映射的持久层框架。 mybatis消除了几乎所有的jdbc代码和参数的手工设置以及对结果集的检索封装。 mybatis...

mybatis是支持普通sql查询、存储过程和高级映射的持久层框架。

mybatis消除了几乎所有的jdbc代码和参数的手工设置以及对结果集的检索封装。

mybatis可以使用 简单的xml或注解用于配置和原始映射,将接口和java的pojo(plain old java objects 普通的java对象)映射成数据库中的记录。

每一个mybatis应用程序都以一个sqlsessionfactory对象的实例为核心。

sqlsessionfactory对象的实例可以通过sqlsessionfactorybuilder对象来获得。sqlsessionfactorybuilder对象可以通过xml配置文件,或从以往使用管理中准备好的configuration类实例中来构建sqlsessionfactory对象。

【示例:使用配置类获取sqlsessionfactory】

datasource datasource = blogdatasourcefactory.getblogdatasource();
transactionfactory transactionfactory = new jdbctransactionfactory();
//环境
environment environment = new environment("development", transactionfactory, datasource);
configuration configuration = new configuration(environment);
//映射器类
configuration.addmapper(blogmapper.class);
sqlsessionfactory sqlsessionfactory = new sqlsessionfactorybuilder().build(configuration);

注意这种情况下配置是添加映射器类。映射器类是java类,这些类包含sql映射语句的注解从而避免了xml文件的依赖,但是xml映射仍然在 大多数高级映射(比如:嵌套join映射)时需要。

出于这样的原因,如果存在xml配置文件的话,mybatis将会自动查找和加载一个对等的xml文件(这种情况下,基于类路径下的blogmapper.class类的类名,那么blogmapper.xml将会被加载–即class 与 xml在同一个文件目录下。如果非,则需要手动配置加载xml)。

【1】基本增删改查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.web.mapper.usermapper">

   <!-- 可以解决model属性名与数据表中column列名不一致问题 jdbctype一定要大写 -->  
   <resultmap type="user" id="usermap">
    <id property="id" column="id" javatype="int" jdbctype="integer"/>
    <result property="name" column="username" javatype="string" jdbctype="varchar"/>
    <result property="age" column="age" javatype="int" jdbctype="integer"/>
   </resultmap>

   <!--
   注意这里的result,如果column == property 则可以直接返回java object。
   如果属性名与列名不一致,解决方法如下:
   1. 使用resultmap; 
   2.返回hashmap ; 
   3.查询语句使用别名
   -->
   <select id="getuser" parametertype="int" resultmap="usermap">
    select * from t_user where id=#{id}
   </select>

   <delete id="deleteuser" parametertype="int" >
    delete from t_user where id=#{id}
   </delete>


   <update id="updateuser" parametertype="user" >
    update t_user set username=#{name},age=#{age} where id=#{id}
   </update>

   <insert id="insertuser" parametertype="user" >
    insert into t_user(username,age) values(#{name},#{age})
   </insert>

   <!-- model's attr(name) different from column(username), so the result use usermap -->

   <select id="getusers" resultmap="usermap">
    select * from t_user
   </select>
</mapper>

注册到mybatis.xml [当与spring结合时,将不需要这个配置文件]

mybatis的配置文件

<?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="jdbc.properties"/>

  <!-- 配置实体类的别名 -->
  <typealiases>
    <!-- <typealias type="com.web.model.user" alias="user"/> -->
    <package name="com.web.model"/>
  </typealiases>
<!-- 
  development : 开发模式
  work : 工作模式
 -->
  <environments default="development">
    <environment id="development">
      <transactionmanager type="jdbc" />
      <datasource type="pooled">
        <property name="driver" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
      </datasource>
    </environment>
  </environments>

  <mappers>
    <mapper resource="com/web/mapper/usermapper.xml"/>
    <mapper resource="com/web/mapper/ordermapper.xml"/>
    <mapper class="com.web.mapperclass.usermapper"/>
  </mappers>
</configuration>

【2】通过sqlsessionfactory拿到session

这里使用xml文件获取sqlsessionfactory和sqlsession。

public static sqlsessionfactory getfactory(){
	/* flow the src dir*/
	string resource = "mybatis.xml";
	/*mybatisutils.class.getresourceasstream(resource)----- it's wrong !!!!
     * please distinguish the two up and down 
     * */
	inputstream inputstream = mybatisutils.class.getclassloader().getresourceasstream(resource);
	sqlsessionfactory factory = new sqlsessionfactorybuilder().build(inputstream);
	return factory;
}
sqlsession session = factory.opensession(true);
//默认手动提交;
/*
  两种解决方式:
  1.factory.opensession(true);
  2.session.commit();
  */

【3】增删改查后台测试代码

/*use sql xml not annotation*/
@test
  public void testadd(){
	sqlsession session = mybatisutils.getfactory().opensession();
	string statement = "com.web.mapper.usermapper.insertuser";
	/*return the effect rows*/
	int insert= session.insert(statement, new user("tom5", 15));
	/*default is not auto commit*/
	session.commit(true);
	session.close();
	system.out.println("effect rows.."+insert);
}
@test
  public void testselect(){
	/*set auto commit ,which equals to the above*/
	sqlsession session = mybatisutils.getfactory().opensession(true);
	string statement = "com.web.mapper.usermapper.getuser";
	/*return the effect rows*/
	user user = session.selectone(statement, 3);
	system.out.println("effect rows.."+user);
}
@test
  public void testupdate(){
	sqlsession session = mybatisutils.getfactory().opensession(true);
	string statement = "com.web.mapper.usermapper.updateuser";
	/*return the effect rows*/
	int update= session.update(statement, new user(3,"tom4", 13));
	system.out.println("effect rows.."+update);
}
@test
  public void testdelete(){
	sqlsession session = mybatisutils.getfactory().opensession();
	string statement = "com.web.mapper.usermapper.deleteuser";
	/*return the effect rows*/
	int delete= session.delete(statement, 6);
	/* commit by yourself*/
	session.commit();
	system.out.println("effect rows.."+delete);
	session.close();
}
@test
  public void testgetusers(){
	sqlsession session = mybatisutils.getfactory().opensession();
	string statement = "com.web.mapper.usermapper.getusers";
	/*return the list<user>*/
	list<user> users= session.selectlist(statement);
	session.commit();
	system.out.println("effect rows.."+users);
	session.close();
}

tips :

parametertype 和 resulttype 为 hashmap :

  • mapper.xml :
<select id="getuserformap" parametertype="hashmap" resulttype="hashmap">
    select * from c_user where id=#{id};
  </select>
  • test code :
@test
  public void getuserformap(){
	sqlsession session = mybatisutils.getfactory().opensession();
	string statement = "com.web.mapper.usermapper.getuserformap";
	hashmap<string, object> map = new hashmap<string, object>();
	map.put("id", 1);
	/*return the effect rows*/
	object selectone = session.selectone(statement, map);
	/*default is not auto commit*/
	session.commit(true);
	session.close();
	system.out.println("effect rows.."+selectone+" ,class :"+selectone.getclass());
}
  • result as follows :
effect rows..{id=1, age=12, name=luli} ,class :class java.util.hashmap

综上可知:mybatis 会根据参数类型和结果类型,自动进行解析封装。

【扩展 基本方法】

【1】分页列表

 <select id="getlistpage" parametertype="hashmap" resultmap="siteextenddaomap">
    select id,site_id,site_name,site_number,province,city,area,address,internal_number,longitude,latitude
    from tb_site
    --使用动态sql
    <trim prefix="where" prefixoverrides="and |or "> 
      <if test="checkstate!= null and checkstate!=''">
        and check_state = #{checkstate,jdbctype=integer}
      </if>
      <if test="siteid!= null and siteid!=''">
        and site_id like concat('%',#{siteid},'%')
      </if>
      <if test="sitename!= null and sitename!=''">
        and site_name like concat('%',#{sitename},'%')
      </if>
      <if test="sitenumber!= null and sitenumber!=''">
        and site_number like concat('%', #{sitenumber},'%')
      </if>
      <if test="province!= null and province!=''">
        and province = #{province}
      </if>
      <if test="city!= null and city!=''">
        and city = #{city}
      </if>
      <if test="area!= null and area!=''">
        and area = #{area}
      </if>
    </trim> 
    --添加排序
    <if test="sortname!= null and sortname!='' and sortorder!= null and sortorder!=''">
      order by ${sortname} ${sortorder}
    </if>
    --添加分页
    limit ${(page-1)*pagesize},${pagesize}
 </select>

【2】删除方法–根据对象或者id

如果参数为pojo,mybatis会自动从对象里面获取id ;

  <delete id="delete" parametertype="user">
    delete from tb_user
    where
    id = #{id} 
  </delete>

  <delete id="deletebyid" parametertype="long">
    delete from tb_user
    where
    id = #{id} 
  </delete>

【3】根据 id list 删除数据

  <delete id="deletebyids">
    delete from tb_user
    where id in
    --使用foreach
    <foreach collection="list" item="id" open="(" separator=","close=")"> #{id} 
    </foreach>
  </delete>

【4】getrows

通常与getlistpage联合使用。

<select id="getrows" parametertype="hashmap" resulttype="long">
    select count(*) from tb_sys_role
    <if test="keysysrole!= null">
      <trim prefix="where" prefixoverrides="and |or ">
        <if test="keysysrole.id!= null">
        and id = #{keysysrole.id}
        </if>
        <if test="keysysrole.name!= null and keysysrole.name!=''">
        and name = #{keysysrole.name}
        </if>
        <if test="keysysrole.available!= null and keysysrole.available!=''">
        and available = #{keysysrole.available}
        </if>
      </trim>
    </if>
  </select>

总结

以上就是本文关于mybatis使用xml进行增删改查代码解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!