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 基础知识梳理( ...
随机推荐
- Image Style Transfer:多风格 TensorFlow 实现
·其实这是一个选修课的present,整理一下作为一篇博客,希望对你有用.讲解风格迁移的博客蛮多的,我就不过多的赘述了.讲一点几个关键的地方吧,当然最后的代码和ppt也希望对你有用. 1.引入: 风格 ...
- python写一个md5解密器
前言: md5解密,百度了一下发现教程不是很多也不详细. 这个图都没一张...跳转地址:点我 0x01 windows环境,kali也可以啊 burpsuite requests模块 bs4模块 0x ...
- S5PV210时钟,看门狗定时器
晶振:时钟源(操作主要有两个,倍频,分频) A8的时钟源: 时钟域,每个时钟域(不同的最高频率和最低频率)管理着不同的电路模块: 不同的时钟域对应不同电路模块表 时钟电路:懂得看时钟电路(时钟源选择开 ...
- 【解决问题】SSH连不上Ubuntu虚拟机解决办法
1. 安装openssh-client Ubuntu默认缺省安装了openssh-client,apt-get安装即可 sudo apt-get install openssh-client 2. 安 ...
- 浅谈format格式化输出
什么是format? 相对于基本格式化输出采用"%"的方法,format的功能强大,该函数把字符串当一个模板,通过传入的参数进行格式化,并且使用大括号"{}"作 ...
- Python个人总结_02
个人学习总结: python 第二课 解释型和编译型语言 计算机是不能够识别高级语言的,当我们运行一个高级语言的时候,需要将高级语言 翻译成计算机能够读懂的机器语言.这个过程分为两类,一个是编译,一个 ...
- Java经典编程题50道之五
利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示. public class Example05 { public static ...
- qdoc.exe
qdoc.exe Usage: qdoc [options] file1.qdocconf ... # Qt文档生成器 Qt documentation generator # 设置 Options: ...
- HDU - 1789 贪心
贪心策略:按照分数降序排列,如果分数相同将截止时间早的排在前面.每次让作业尽量晚完成,因此需要逆序枚举判断这一天是否已经做了其他作业,如果没时间做这个作业说明不能完成,否则将这一天标记. AC代码 # ...
- init启动进程
init启动进程需要读取()配置文件 1,启动init进程的配置文件是/etc/inittab 2,/etc/sysvinit是系统初始化用的 /sbin/init在核心完整的加载后,开始运行系统 ...