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对象(属性:idname

调用持久层对象的存储方法 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基础知识的更多相关文章

  1. Ibatis基础知识:#与$的差别

    背景 Ibatis是一个轻量级.非侵入式的持久层框架,适用于范围较广.较轻便--当然,不管J2EE中哪一个持久层框架,都会基于JDBC(不细究JNDI方式).我们在SqlMap中编写SQL,利用各种S ...

  2. Mybatis/ibatis基础知识

    Tip:mapper.xml中sql语句不允许出现分号! 1.#和$符号的区别 #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号.如:order by #user_id#,如果传入的值是 ...

  3. spring 基础知识复习

    spring是一个分层架构,由 7 个定义良好的模块组成.Spring 模块构建在核心容器之上,核心容器定义了创建.配置和管理 bean 的方式. 组成spring框架的每个模块(或组件)都可单独存在 ...

  4. .NET面试题系列[1] - .NET框架基础知识(1)

    很明显,CLS是CTS的一个子集,而且是最小的子集. - 张子阳 .NET框架基础知识(1) 参考资料: http://www.tracefact.net/CLR-and-Framework/DotN ...

  5. RabbitMQ基础知识

    RabbitMQ基础知识 一.背景 RabbitMQ是一个由erlang开发的AMQP(Advanced Message Queue )的开源实现.AMQP 的出现其实也是应了广大人民群众的需求,虽然 ...

  6. Java基础知识(壹)

    写在前面的话 这篇博客,是很早之前自己的学习Java基础知识的,所记录的内容,仅仅是当时学习的一个总结随笔.现在分享出来,希望能帮助大家,如有不足的,希望大家支出. 后续会继续分享基础知识手记.希望能 ...

  7. selenium自动化基础知识

    什么是自动化测试? 自动化测试分为:功能自动化和性能自动化 功能自动化即使用计算机通过编码的方式来替代手工测试,完成一些重复性比较高的测试,解放测试人员的测试压力.同时,如果系统有不份模块更改后,只要 ...

  8. [SQL] SQL 基础知识梳理(一)- 数据库与 SQL

    SQL 基础知识梳理(一)- 数据库与 SQL [博主]反骨仔 [原文地址]http://www.cnblogs.com/liqingwen/p/5902856.html 目录 What's 数据库 ...

  9. [SQL] SQL 基础知识梳理(二) - 查询基础

    SQL 基础知识梳理(二) - 查询基础 [博主]反骨仔 [原文]http://www.cnblogs.com/liqingwen/p/5904824.html 序 这是<SQL 基础知识梳理( ...

随机推荐

  1. BZOJ 1758: [Wc2010]重建计划 [暂时放弃]

    今天晚上思维比较乱,以后再写写吧#include <iostream> #include <cstdio> #include <cstring> #include ...

  2. SDN第五次上机作业

    作业链接 1.建立拓扑,并连接上ODL控制器. 2.利用ODL下发组表.流表,实现建议负载均衡 查看s2接收的数据包都被drop掉了 在s1中下发组表 在s1中下发流表使组表生效 下发流表覆盖S2中d ...

  3. SDN第三次作业

    作业链接 阅读文章:http://www.sdnlab.com/19777.html 阅读<重构网络>第一二章 列举openflow1.0的12元组? 入端口 源MAC地址 目的MAC地址 ...

  4. CSS学习(一)---使用CSS的四种方式

      1. 行内样式 例: <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

  5. Sublime 远程连接 Linux服务器

    Sublime是一款强大的编辑器,它的强大体现在它强大的插件. 要实现Sublime 远程连接 Linux服务器,需要使用插件SFTP. 一. 插件安装 用Package Control安装插件按下C ...

  6. 数据与C

    //以十进制.八进制和十六进制输出100,加入#会显示前缀#include<stdio.h>int main(){ int x = 100; printf("dec = %d; ...

  7. 使用PowerDesigner对NAME和COMMENT互相转换

    本文来自我的github pages博客http://galengao.github.io/ 即www.gaohuirong.cn 在使用PowerDesigner对数据库进行概念模型和物理模型设计时 ...

  8. 教我徒弟Android开发入门(二)

    前言: 上一期实现了简单的QQ登录效果,这一期继续对上一期进行扩展 本期的知识点: Toast弹窗,三种方法实现按钮的点击事件监听 正文:   Toast弹窗其实很简单,在Android Studio ...

  9. ubuntu命令行下java工程编辑与算法(第四版)环境配置

    ubuntu命令行下java工程编辑与算法(第四版)环境配置 java 命令行 javac java 在学习算法(第四版)中的实例时,因需要安装配套的java编译环境,可是在编译java文件的时候总是 ...

  10. JVM中对象访问定位两种方式

    1.通过句柄方式访问, 在Java堆中分出一块内存进行存储句柄池,这样的话,在栈中存储的是句柄的地址 优点: 当对象移动的时候(垃圾回收的时候移动很普遍),这样值需要改变句柄中的指针,但是栈中的指针不 ...