如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中:

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version>
</dependency>

配置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> <!-- 别名
.类型别名 typeAlias type属性值为全类名 alias为别名
.根据包 name属性值为包名 别名为包内类名的小写
-->
<typeAliases>
<!-- <typeAlias type="com.tzh.bean.Clazz" alias="clazz"/>
<typeAlias type="com.tzh.bean.Student" alias="student"/> -->
<package name="com.tzh.bean"/>
</typeAliases> <environments default="default">
<environment id="default">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:///1606a" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/tzh/mapper/*.xml" />
</mappers> </configuration>

创建beanSession工厂

每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。

package com.tzh.test;

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; public class SqlSessionUtils { public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
try {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); sqlSession = sqlSessionFactory.openSession();
} catch (Exception e) {
e.printStackTrace();
}
return sqlSession;
}

创建mapper接口

package com.tzh.mapper;

import java.util.List;

import com.tzh.bean.Student;

public interface StuMapperDao {

    List<Student> getStuList(Student student);
List<Student> getStuListChoose(Student student); int updateStu(Student student); int addStu(List<Student> stuList ); int delStu(int [] arr);
}

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">
<!-- namespace 对应的是接口的全名 -->
<mapper namespace="namespace">
<!-- student为别名 在核心配置文件设置 -->
<select id="getStuList" resultType="student" parameterType="student"> select * from 0802_stu
<!-- where = -->
<!-- 如果内部的判断条件成立,会自动加上where关键字,并且会把多余的and或者or去掉 -->
<where>
<if test="sname !=null and sname!='' ">
and sname like concat('%',#{sname},'%')
</if> <if test="sex!=null and sex!=''">
and sex =#{sex}
</if>
<if test="age >0 ">
and age &lt; #{age}
</if>
</where>
</select>
<select id="getStuListChoose" resultType="student"
parameterType="student"> select * from 0802_stu
<!-- where = -->
<!-- 如果内部的判断条件成立,会自动加上where关键字,并且会把多余的and或者or去掉 -->
<!-- <where> -->
<trim prefix="where" prefixOverrides="and |or ">
<!-- 条件成立在前面加上WHER关键词 并 prefixOverrides前缀覆盖 条件成立去挑前缀add|or--> <!-- choose when otherwise 用法和switch case break 类似 只运行一个条件都符合时运行第一个 -->
<choose>
<when test="sname !=null and sname!='' ">
and sname like concat('%',#{sname},'%')
</when>
<when test="sex!=null and sex!=''">
and sex =#{sex}
</when>
<otherwise><!-- 其他相当于else -->
and age &lt; #{age}
</otherwise>
</choose>
</trim>
<!-- </where> -->
</select> <update id="updateStu" parameterType="student">
update 0802_stu
<!-- SET 在内部的条件成立,就会加上set关键字,并且会把多余的逗号去掉 -->
<!-- <set> -->
<trim prefix="set" suffixOverrides=",">
<!-- suffixOverrides 去掉多余的 , -->
<if test="sname != null and sname !=''">
sname = #{sname},
</if>
<if test="sex !=null and sex != ''">
sex = #{sex},
</if>
<if test="age>0">
age = #{age}
</if>
</trim>
<!-- </set> -->
where sid= #{sid}
</update> <insert id="addStu" parameterType="list">
INSERT into 0802_stu (sname,sex,age,cid) VALUES
<!-- 你可以传递一个 List 实例或者数组作为参数对象传给 MyBatis。
当你这么做的时 候,MyBatis 会自动将它包装在一个 Map 中,用名称在作为键。
List 实例将会以“list” 作为键,而数组实例将会以“array”作为键。 -->
<foreach collection="list" item="stu" separator=",">
(#{stu.sname},#{stu.sex},#{stu.age},#{stu.cid})
</foreach> <!-- ('隆多','男',,),
('隆多','男',,),
('隆多','男',,),
('隆多','男',,),
('隆多','男',,),
('隆多','男',,) --> </insert> <delete id="delStu" parameterType="java.lang.reflect.Array">
DELETE FROM 0802_stu WHERE sid in
<foreach collection="array" item="sid" open="(" separator="," close=")" >
#{sid}
</foreach>
</delete> </mapper>

测试

package com.tzh.test;

import java.util.ArrayList;
import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import com.tzh.bean.Student;
import com.tzh.mapper.StuMapperDao; public class TestDemo { @Test
public void testListLike() { SqlSession sqlSession = SqlSessionUtils.getSqlSession();
StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
Student student = new Student();
student.setSname("k");
student.setSex("男");
student.setAge(); //List<Student> stuList = mapper.getStuList(student);
List<Student> stuList = mapper.getStuListChoose(student);
for (Student student2 : stuList) {
System.out.println(student2);
} } @Test
public void testUpdate() { SqlSession sqlSession = SqlSessionUtils.getSqlSession();
StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
Student student = new Student();
student.setSname("k");
student.setSex("男");
//student.setAge(34);
student.setSid(); int updateStu = mapper.updateStu(student);
sqlSession.commit();
} @Test
public void testAdd() { SqlSession sqlSession = SqlSessionUtils.getSqlSession();
StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class);
Student student = new Student();
student.setSname("k");
student.setSex("男");
student.setAge();
student.setCid();
Student student1 = new Student();
student1.setSname("k");
student1.setSex("男");
student1.setAge();
student1.setCid();
Student student2 = new Student();
student2.setSname("k");
student2.setSex("男");
student2.setAge();
student2.setCid(); List<Student> stuList = new ArrayList<Student>(); stuList.add(student);
stuList.add(student1);
stuList.add(student2); int addStu = mapper.addStu(stuList); sqlSession.commit(); } @Test
public void testDel() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
StuMapperDao mapper = sqlSession.getMapper(StuMapperDao.class); int [] arr = {,,,,}; int delStu = mapper.delStu(arr);
sqlSession.commit();
} }

mybatis学习(一)不使用 XML 构建 SqlSessionFactory的更多相关文章

  1. mybatis源码探索笔记-1(构建SqlSessionFactory)

    前言 mybatis是目前进行java开发 dao层较为流行的框架,其较为轻量级的特性,避免了类似hibernate的重量级封装.同时将sql的查询与与实现分离,实现了sql的解耦.学习成本较hibe ...

  2. mybatis学习记录三——SqlMapConfig.xml相关参数详解

      5       SqlMapConfig.xml mybatis的全局配置文件SqlMapConfig.xml,配置内容如下: properties(属性) settings(全局配置参数) ty ...

  3. Mybatis学习(三)XML配置文件之mybatis-config.xml

    1.MyBatis的配置文件结构 1.1 properties 这些是外部化的,可替代的属性,这些属性也可以配置在典型的 Java 属性配置文件中,或者通过 properties 元素的子元素来传递. ...

  4. Mybatis学习(二)常用对象SqlSessionFactory和SqlSession

    1.SqlSessionFactory SqlSeesionFactory对象是MyBatis的关键对象,它是一个数据库映射关系经过编译后的内存镜像. SqlSeesionFactory对象的实例可以 ...

  5. mybatis学习一:基于xml与注解配置入门实例与问题

    注:本case参考自:http://www.cnblogs.com/ysocean/p/7277545.html 一:Mybatis的介绍: MyBatis 本是apache的一个开源项目iBatis ...

  6. Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)

    一.parameterType(输入类型) 1.1 传递简单类型 <!-- 根据用户id查询用户 --> <select id="queryUserById" p ...

  7. MyBatis学习笔记3--使用XML配置SQL映射器

    <resultMap type="Student" id="StudentResult"> <id property="id&quo ...

  8. 【MyBatis学习05】SqlMapConfig.xml文件中的配置总结

    经过上两篇博文的总结,对mybatis中的dao开发方法和流程基本掌握了,这一节主要来总结一下mybatis中的全局配置文件SqlMapConfig.xml在开发中的一些常用配置,首先看一下该全局配置 ...

  9. Mybatis学习笔记(四) —— SqlMapConfig.xml配置文件

    一.properties(属性) SqlMapConfig.xml可以引用java属性文件中的配置信息 在config下定义db.properties文件,如下所示: db.properties配置文 ...

随机推荐

  1. 【Springboot】Springboot整合Ehcache

    刚刚项目上线了,记录下使用的技术...... EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. Ehcache的特点 ( ...

  2. jmeter-模板报错-Fatal Error! com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 2 字节的 UTF-8 序列的字节 2 无效

    使用的模板不能有中文!!!!检查模板.

  3. js获取服务器端时间

    第一种: $.ajax({ type:"OPTIONS", url:"/", complete:function(x){ var date = x.getRes ...

  4. js差异化继承

    var parentObj={ name:"123456", get_name:function(){ return this.name; }, says:function(){ ...

  5. Dell PowerEdge服务器RAID卡驱动下载

    Dell PowerEdge服务器RAID卡驱动下载 DELL新阵列卡驱动下载 型号 支持系统驱动 H310/710 /710P/810 Win2008 x32 Windows 2008 x64 Wi ...

  6. Jmeter函数 参数

    1.time时间函数 ${__time(,)} 1450056496991 //无格式化参数,返回当前毫秒时间 ${__time(/1000,)} //返回当前时间为秒 ${__time(yyyyMM ...

  7. Go 结构体与初始化

    Go 通过类型别名(alias types)和结构体的形式支持用户自定义类型. 结构体是复合类型,当需要定义类型,它由一系列属性组成,每个属性都有自己的类型和值的时候,就应该使用结构体,它把数据聚集在 ...

  8. Nginx之监控进程和工作进程

    1. 函数调用分析 在开启 master 的情况下,多进程模型的下的入口函数为 ngx_master_process_cycle,如下: int mian() { ... if (ngx_proces ...

  9. js 处理url参数,应用导航分类

    1.先上图 2.代码 html <li><a href="javascript:void(0);" data-cid = "{$v['id']}&quo ...

  10. 微信小程序之地址联动

    这就是我们要实现的效果 <view class="consignee"> <!-- consignee 收件人 --> <text>收件人: & ...