mybatis学习(一)不使用 XML 构建 SqlSessionFactory
如果使用 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 < #{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 < #{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的更多相关文章
- mybatis源码探索笔记-1(构建SqlSessionFactory)
前言 mybatis是目前进行java开发 dao层较为流行的框架,其较为轻量级的特性,避免了类似hibernate的重量级封装.同时将sql的查询与与实现分离,实现了sql的解耦.学习成本较hibe ...
- mybatis学习记录三——SqlMapConfig.xml相关参数详解
5 SqlMapConfig.xml mybatis的全局配置文件SqlMapConfig.xml,配置内容如下: properties(属性) settings(全局配置参数) ty ...
- Mybatis学习(三)XML配置文件之mybatis-config.xml
1.MyBatis的配置文件结构 1.1 properties 这些是外部化的,可替代的属性,这些属性也可以配置在典型的 Java 属性配置文件中,或者通过 properties 元素的子元素来传递. ...
- Mybatis学习(二)常用对象SqlSessionFactory和SqlSession
1.SqlSessionFactory SqlSeesionFactory对象是MyBatis的关键对象,它是一个数据库映射关系经过编译后的内存镜像. SqlSeesionFactory对象的实例可以 ...
- mybatis学习一:基于xml与注解配置入门实例与问题
注:本case参考自:http://www.cnblogs.com/ysocean/p/7277545.html 一:Mybatis的介绍: MyBatis 本是apache的一个开源项目iBatis ...
- Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)
一.parameterType(输入类型) 1.1 传递简单类型 <!-- 根据用户id查询用户 --> <select id="queryUserById" p ...
- MyBatis学习笔记3--使用XML配置SQL映射器
<resultMap type="Student" id="StudentResult"> <id property="id&quo ...
- 【MyBatis学习05】SqlMapConfig.xml文件中的配置总结
经过上两篇博文的总结,对mybatis中的dao开发方法和流程基本掌握了,这一节主要来总结一下mybatis中的全局配置文件SqlMapConfig.xml在开发中的一些常用配置,首先看一下该全局配置 ...
- Mybatis学习笔记(四) —— SqlMapConfig.xml配置文件
一.properties(属性) SqlMapConfig.xml可以引用java属性文件中的配置信息 在config下定义db.properties文件,如下所示: db.properties配置文 ...
随机推荐
- 题解 【POJ1157】LITTLE SHOP OF FLOWERS
先把题目意思说一下: 你有F束花,编号为\(1\)~\(F\)(\(1<=F<=100\)),\(V\)个花瓶,编号为\(1\) ~\(V\)(\(1<=V<=100\)), ...
- electron-vue [Vue warn]: Failed to resolve directive: decorator
electron-vue引入ant-desigin-vue使用ant自定义指令 v-decorator报销 <a-form-item> <a-input v-decorator=&q ...
- 清除Tomcat缓存
删除tomcat目录下的缓存文件分别位于: tomcat/work tomcat/temp ...
- vue模板语法下集
1. 样式绑定 1.1 class绑定 使用方式:v-bind:class="expression" expression的类型:字符串.数组.对象 1.2 style绑定 v-b ...
- noi.ac #536 打地鼠
题目链接:戳我 [问题描述] 小A在玩打地鼠游戏.有一个n×m的网格,每个位置上地鼠都会要么冒出头要么缩进去.地鼠很狡猾,每次小A选一个地鼠冒出头的格子(x,y)把它打下去,但同一行同一列的地鼠全都会 ...
- Teamviewer解决许可证授权的问题
提交商业用途表 https://www.teamviewer.com/zhCN/pricing/commercial-use/
- BeanFactory和ApplicationContext的区别+部分Spring的使用
BeanFactory和ApplicationContext的区别 ApplicationContext 方式加载:创建容器的同时 容器初始化,容器所有的bean创建完毕 Spring容器中获取一 ...
- springboot拦截异常信息发送邮件提醒
-- private JavaMailSender sender; 可能会出现注入错误,请注意yam配置文件中格式是否一致:否则会找不到注入的bean 一 发送邮件 在Springboot中发送邮件非 ...
- C++ 编程风格指南
C++ Programming Style Guidelines 他人翻译中文版:click 让程序具有好的可读性 “避免日后 有人(或者自己)指着你的代码骂娘:这特么谁写的破烂 玩意”(来自:知乎- ...
- 收集的21个优秀的学习资源Kotlin
一.教程 1.The Kotlin Website Kotlin 官方网站(英文) 2.Kotlin editor Kotlin 在线编辑器 3.Keddit:在开发Android应用程序时学习K ...