iBatis基础知识
iBatis简介:
特点:结构性好,小巧,容易上手
搭建环境:
1、创建java 项目
2、导入(3个)jar包:ibatis-2.3.0.667.jar,mysql驱动包,Junit测试包
3、配置iBatis的主配置文件 SqlMapConfig.xml
配置由jdbc管理事务
配置数据源 SIMPLE
配置编写sql语句的xml文件 <sqlMap resource=”cn/Stu.xml”/>
4、编写Jdbc 连接的属性文件 SqlMap.properties
5、编写每个实体的映射文件(Map 文件)----里面定义和方法对应的sql语句
SqlMapConfig.xml配置文件中的信息:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<!-- 引用JDBC属性的配置文件-->
<properties resource="com/iflytek/entity/SqlMap.properties" />
<!-- 使用JDBC的事务管理 -->
<transactionManager type="JDBC">
<!-- 数据源 -->
<dataSource type="SIMPLE">
<!-- <property name="JDBC.Driver" value="${driver}" /> -->
<property value="com.mysql.jdbc.Driver" name="JDBC.Driver" />
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:
3306/ibatisstudent" />
<property name="JDBC.Username" value="root" />
<property name="JDBC.Password" value="mysql" />
</dataSource>
</transactionManager>
<!-- 这里可以写多个实体的映射文件 -->
<sqlMap resource="com/iflytek/entity/Student.xml" />
</sqlMapConfig>
iBatis必须要有持久层,在持久层读取主配置文件,生成sqlMapClient对象,完成对数据库的增删改查操作。
iBatis插入字段或者给字段赋值,使用: #字段名# eg: #id#
Date日期类型自动赋值: Date.valueOf(“2017-09-09”)
iBatis的增删改查
private static SqlMapClient sqlMapClient = null;
// 在静态代码块读取配置文件,生成SqlMapClient 对象
static { try {
Reader reader = Resources.getResourceAsReader
("com/iflytek/entity/SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
增加数据到数据库中:
//持久层的代码
public boolean addStudent(Student student) {
Object object = null;
boolean flag = false;
try { //addStudent:指xml文件中<insert>标签的id标识
student:是指<insert>标签的parameterClass类型的变量
object = sqlMapClient.insert("addStudent", student);
System.out.println("添加学生信息的返回值:" + object);
} catch (SQLException e) {
e.printStackTrace();
}
在xml中的配置:(主键数据库自动生成)
<insert id="addStudent" parameterClass="Student">
insert into t_student(name,birth,score)
values (#name#,#birth#,#score#);
//<selectKey>标签用于查询出从数据库中自动生成的主键id字段
<!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: -->
<!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->
<!-- mssql:select @@IDENTITY as value -->
<!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->
<!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。
有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->
<selectKey resultClass="int" keyProperty="id">
select @@identity as value
</selectKey>
</insert>
删除数据库中的某条记录:
//持久层的代码
public boolean deleteStudentById(int id) {
boolean flag = false;
Object object = null;
try { //deleteStudentById:指xml文件中<delete>标签的id标识
id:是指<delete>标签的parameterClass类型的变量
object = sqlMapClient.delete("deleteStudentById", id);
System.out.println("删除学生信息的返回值:" + object + ",这里返回的是影响的行数");
} catch (SQLException e) {
e.printStackTrace();
}
}
在xml中的配置:
<delete id="deleteStudentById" parameterClass="int">
delete from t_student where id=#id#
</delete>
修改数据库表中的记录:
//持久层的代码
public boolean updateStudent(Student student) {
boolean flag = false;
Object object = false;
try { //updateStudent:指xml文件中<update>标签的id标识
student:是指<update>标签的parameterClass类型的变量
object = sqlMapClient.update("updateStudent", student);
System.out.println("更新学生信息的返回值:" + object + ",返回影响的行数");
} catch (SQLException e) {
e.printStackTrace();
}
在xml文件中的配置信息:
<update id="updateStudent" parameterClass="Student">
update t_student set name=#name#, birth=#birth#,
score=#score# where id=#id#
</update>
根据id查询数据库中的记录:
持久层的代码:
public Student selectStudentById(int id) {
Student student = null;
try { //selectStudentById:指xml文件中<select>标签的id标识
id:是指<select>标签的parameterClass类型的变量
Student :指<select>标签中的resultClass类型的变量
student = (Student) sqlMapClient.queryForObject(
"selectStudentById", id);
} catch (SQLException e) {
e.printStackTrace();
}
Xml文件中的配置:
<select id="selectStudentById" parameterClass="int" resultClass= "Student">
select * from t_student where id=#id#
</select>
查询出数据库中所有的Student对象:
持久层的代码:
public List<Student> selectAllStudent() {
List<Student> students = null;
try { //selectAllStudent:指xml文件中<select>标签的id标识
List<Student>:指<select>标签中的resultClass类型的变量
students = sqlMapClient.queryForList("selectAllStudent");
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
Xml的配置文件:
<!-- id表示select里的sql语句,resultClass表示返回结果的类型
每查到一条记录就生成Student对象,放到list集合中
然后将list集合返回到持久层的集合中
-->
<select id="selectAllStudent" resultClass="Student">
select * from t_student
</select>
iBatis的关联映射Many-to-one:
存储关系:
手动建表,建立many-to-one的映射关系
存储Group对象(属性:id,name)
调用持久层对象的存储方法 addGroup(group)存储Group对象
持久层对象: 一加载持久层类,读取SqlMapConfig.xml文件信息,用来生成sqlMapClient对象,用来完成对数据库的操作
执行addGroup方法
sqlMapClient.insert(“addGroup”,group);
addGroup:是sql语句映射的id
group:是sql语句的映射的parameterClass
存储User对象(属性:id ,name,group)
执行addUser方法
sqlMapClient.insert(“addUser”,user);
addUser:是sql语句映射的id
user:是sql语句的映射的parameterClass
在xml文件中的sql语句的配置:
<insert id=”addUser”parameterClass=”User”>
insert into t_user(name,groupid) values(#name#,#group.id#)
//表示当前User对象在数据库中的记录为id自动生成,取得数据库中的记录
<selectKey resultClass="int" keyProperty="id">
select @@identity as value
</selectKey>
</insert>
加载关系:
sqlMapClient.queryForList("selectUserById",id); //查找User对象
<select id=”selectUserById” parameterClass=”int” resultMap=”tem”>
Select * from t_user where id=#id#
</select>
<resultMap id=”tem” resultClass=”User”>
Property :当前User对象的属性名
Column:存储在t_user表中的字段名
jdbcType:存储在数据库中的字段类型
<result column=”id” property=”id” jdbcType=”int”> </result>
<result column=”name” property=”name” jdbcType=”varchar”/>
Select:表示再次调用selectGroupById这个方法,通过外键groupid,外找主,找到groupid对应的记录,生成group对象,放到group属性上
<result property=”group” column=”groupid” select=”selectGroupById”> </result>
</result>
</resultMap>
iBatis的关联映射one-to-one:
存储关系:
存储IdCard对象,主键id自动生成
创建Idcard对象,id自动生成
调用持久层对象的方法,addIdCard方法
持久层:sqlMapClient.insert(“addIdCard”,idcard);
Xml中:<insert id=”addIdCard” parameterClass=”IdCard”>
insert into t_idcard(idNum) values(#idNum#)
//取出数据库中自动生成的id,用于给person对象的id赋值
<selectKey resultClass="int" keyProperty="id">
select @@identity as value
</selectKey>
</insert>
存储Person对象,person对象的主键引用idCard的主键
创建Person对象,id去IDcard对象的id
调用持久层对象的方法,addPerson方法
持久层:sqlMapClient.insert(“addPerson”,person);
Xml中:<insert id=”addPerson” parameterClass=”person”>
insert into t_person(id,name) values(#idCard.id#,#name#)
</insert>
加载关系:
sqlMapClient.queryForObject("selectPersonById",id); //查找User对象
<select id=”selectPersonById” parameterClass=”int” resultMap=”tem”>
Select * from t_person where id=#id#
</select>
<resultMap id=”tem” resultClass=”Person”>
Property :当前User对象的属性名
Column:存储在t_user表中的字段名
jdbcType:存储在数据库中的字段类型
<result column=”id” property=”id” jdbcType=”int”> </result>
<result column=”name” property=”name” jdbcType=”varchar”/>
Select:表示再次调用selectIdCardById这个方法,通过主找主,根据id找到t_idCard表中对应的记录,生成IdCard对象,放到idCard属性上
<result property=”idCard” column=”id” select=”selectIdCardById”> </result>
</result>
</resultMap>
iBatis的关联映射many-to-many:
存储关系:
User (属性:id,name ,roles)
Role(属性:id,name)
存储Role对象,主键id自动生成
创建Role对象,id自动生成
调用持久层对象的方法,addRole方法
持久层:sqlMapClient.insert(“addRole”,role);
Xml中:<insert id=”addRole” parameterClass=”Role”>
insert into t_Role(name) values(#name#)
//取出数据库中自动生成的id,用于给第三张表的roleid赋值
<selectKey resultClass="int" keyProperty="id">
select @@identity as value
</selectKey>
</insert>
存储User对象,主键id自动生成
创建User对象,id自动生成
调用持久层对象的方法,addUser方法
持久层:sqlMapClient.insert(“addUser”,role);
Xml中:<insert id=”addUser” parameterClass=”User”>
insert into t_User(name,role) values(#name#,)
//取出数据库中自动生成的id,用于给第三张表的userid赋值
<selectKey resultClass="int" keyProperty="id">
select @@identity as value
</selectKey>
</insert>
存储UserRole对象
加载关系:
查询user用户的id为29的role角色
先查询User对象,
调用sqlMapClient. queryForObject(“selectUserById”,id)
生成User对象, User对象的roles属性需要再次查询;
通过user找到role,需要三张表连接查询,拿到的字段再次将结果封装 ,然后生成role对象,添加到集合中
<resultMap id="CourseTest" class="Course" >
<result column="id" property="id" jdbcType="int" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result property="studentList" column="id" select="getStudentByCourseStudentId"/>
</resultMap>
<select id="selectCourseById" parameterClass="int" resultMap="CourseTest">
select * from t_course where id=#id#
</select>
<select id="getStudentByCourseStudentId" resultMap="getStudentResult"
parameterClass="int">
Select t_student.id,t_student.birth,t_student.name ,t_student.score,
t_student.classid FROM t_student , t_course_student WHERE t_course_student.courseid = #id# AND t_course_student.studentid= t_student.id
</select>
iBatis基础知识的更多相关文章
- Ibatis基础知识:#与$的差别
背景 Ibatis是一个轻量级.非侵入式的持久层框架,适用于范围较广.较轻便--当然,不管J2EE中哪一个持久层框架,都会基于JDBC(不细究JNDI方式).我们在SqlMap中编写SQL,利用各种S ...
- Mybatis/ibatis基础知识
Tip:mapper.xml中sql语句不允许出现分号! 1.#和$符号的区别 #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号.如:order by #user_id#,如果传入的值是 ...
- spring 基础知识复习
spring是一个分层架构,由 7 个定义良好的模块组成.Spring 模块构建在核心容器之上,核心容器定义了创建.配置和管理 bean 的方式. 组成spring框架的每个模块(或组件)都可单独存在 ...
- .NET面试题系列[1] - .NET框架基础知识(1)
很明显,CLS是CTS的一个子集,而且是最小的子集. - 张子阳 .NET框架基础知识(1) 参考资料: http://www.tracefact.net/CLR-and-Framework/DotN ...
- RabbitMQ基础知识
RabbitMQ基础知识 一.背景 RabbitMQ是一个由erlang开发的AMQP(Advanced Message Queue )的开源实现.AMQP 的出现其实也是应了广大人民群众的需求,虽然 ...
- Java基础知识(壹)
写在前面的话 这篇博客,是很早之前自己的学习Java基础知识的,所记录的内容,仅仅是当时学习的一个总结随笔.现在分享出来,希望能帮助大家,如有不足的,希望大家支出. 后续会继续分享基础知识手记.希望能 ...
- selenium自动化基础知识
什么是自动化测试? 自动化测试分为:功能自动化和性能自动化 功能自动化即使用计算机通过编码的方式来替代手工测试,完成一些重复性比较高的测试,解放测试人员的测试压力.同时,如果系统有不份模块更改后,只要 ...
- [SQL] SQL 基础知识梳理(一)- 数据库与 SQL
SQL 基础知识梳理(一)- 数据库与 SQL [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5902856.html 目录 What's 数据库 ...
- [SQL] SQL 基础知识梳理(二) - 查询基础
SQL 基础知识梳理(二) - 查询基础 [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5904824.html 序 这是<SQL 基础知识梳理( ...
随机推荐
- java递归
package com.sun.test; import java.util.ArrayList; import java.util.List; /** * 递归 * */ public class ...
- openvpn服务器一键脚本生成客户端文件
#!/bin/bash #获取参数 while getopts "n:" opt; do case $opt in n) client_name=$OPTARG ;; \?) ;; ...
- WinXP系统下Opencms的安装与配置
1.WinXP系统下安装opencms (1)mysql已安装5.1.40 cmd命令行:mysql -uroot -proot (2)OpenCMS在安装时要求MySQL系统变量“max_al ...
- [翻译] 编写高性能 .NET 代码--第二章 GC -- 减少大对象堆的碎片,在某些情况下强制执行完整GC,按需压缩大对象堆,在GC前收到消息通知,使用弱引用缓存对象
减少大对象堆的碎片 如果不能完全避免大对象堆的分配,则要尽量避免碎片化. 对于LOH不小心就会有无限增长,但LOH使用的空闲列表机制可以减轻增长的影响.利用这个空闲列表,我们可以在两块分配区域中间找到 ...
- Tomcat8+Spring-Security 启用安全通道(https)的一步步实现
近日学习Spring Security框架,学习到利用安全框架完成系统的安全通道控制时,来来回回遇到了不少问题.spring教程上写的略简单,对于我等小白来讲不足以支撑看书编码,好在网络上有资料可以查 ...
- Opencv 3.3.0 常用函数
如何调图像的亮度和对比度? //如何增加图片的对比度或亮度? void contrastOrBrightAdjust(InputArray &src,OutputArray &dst, ...
- 浏览器的 bfcache 特性
一.bfcache 基本概念 现代浏览器在根据历史记录进行前进/后退操作时,会启用缓存机制,名为"bfcache"(back-forward cache,往返缓存),它使页面导航非 ...
- Python+Selenium基础篇之1-环境搭建
Python + Selenium 自动化环境搭建过程 1. 所需组建 1.1 Selenium for python 1.2 Python 1.3 Notepad++ 作为刚初学者,这里不建议使用P ...
- scrapy安装的问题
Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) ...
- 内置函数 -- bytes -- 字节码与字符串相互转换
说明: 1. 返回值为一个新的不可修改字节数组,每个数字元素都必须在0 - 255范围内,是bytearray函数的具有相同的行为,差别仅仅是返回的字节数组不可修改. 2. 当3个参数都不传的时候,返 ...