Mybatis配置及功能详解

一 配置Mybatis
  1. 引入Mybatis的相应的jar包
  2. 配置Mybatis核心配置文件、可以从Mybatis官网下载源码从源码中找到核心配置文件步骤如下:按照官方规定:核心配置文件、和实体类对应user.xml映射,可以建立在自定义的包中如:核心配置文件建立在Config包下 user实体.xml映射简历在Config包下sqlxml包中 ,找到一下如图路径参考上面的配置即可、教你怎么配置
也就是Configuration.xml核心文件、在里面配置jdbc配置等
第二、Dao层的说明、dao层的需求、也就是在Dao需实现什么
dao层的需求:
1、对象能与数据库交互
2、能执行SQL语句
  • Mybatis之sqlsession的作用如下:
SQLsession的作用
1、向SQL语句传入参数
2、执行SQL语句
3、获取执行SQL语句的结果
4、事务的控制
  • 如何得到 SQLsession呢?如下;
1、通过配置文件获取数据库连接相关信息
2、通过配置信息构建SQLsessionFactory
3、通过SqlsessionFactory打开数据库回话
代码如下:也就是工具类
public SqlSession getSqlSession(){
//通过配置文件获取数据库连接信息、用Resources类进行读取
1、Reader reader=Resources.getResourceAsReader("Configuration.xml");注:说明如核心配置文件放在其他地方需手动指定如“com/imooc/config/Configuration.xml”默认自动读取根目录文件src
2、通过配置信息构建一个Sqlsessionfactory
SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
3、通过sqlsessionfactor去打开一个数据库的一个回话
SqlSession sqlsession=sqlsessionfactory.openSession();
return sqlSession;
}
}
}
第三、已经配置好Mybatis核心配置文件以及MybatisDB工具类、如下是配置对应实体对象xml映射文件r让sqlsession读取其配置文件中的内容要求,从而获取数据库中的数据返回给用户。如:实体模型类名叫user、那就是创建user.xml 注:同时也可以建立在接口类中,看个人习惯
代码如下:在第一步、如图找到指定文件夹里有配置文件、跟如下代码一样,参考即可:
<?xml version="1.0" encoding="UTF-8"?>
<!--

Copyright 2009-2016 the original author or authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- mapper的命名空间,相当于sturuts2中 <struts>标签中包名字 packages 包名 -->
<mapper namespace="User">
<!-- 数据库和实体类的对应 type="UserAlias" 类名 如果没有给类去别名,则吧包加类名路径写上-->
<resultMap type="UserAlias" id="UserResult">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="password" jdbcType="VARCHAR" property="password.encrypted"/>
<result column="administrator" jdbcType="BOOLEAN" property="administrator"/>
</resultMap>

<select id="find" parameterType="long" resultMap="UserResult">
SELECT * FROM user WHERE id = #{id:INTEGER}
</select>
<!-- 查询出的数据对应着resultMap标签中的字段属性如果有相应的字段将返回数据没有返回空
parameterType="long" 意思是返回的类型参数,例如你查询的这个方法version(int id,long,org);
那你对这个方法进行操作时,需要进行传参,所以得设置其 parameterType="long" 让配置文件知道你的传参的返回类型,在低层自动帮你设置
-->
<select id="version" parameterType="long" resultType="int">
SELECT version FROM user WHERE id = #{id,jdbcType=INTEGER}
</select>

<delete id="delete" parameterType="UserAlias">
DELETE FROM user WHERE id = #{id:INTEGER}
</delete>

<insert id="insert" parameterType="UserAlias" useGeneratedKeys="false">
INSERT INTO user
( id,
username,
password,
administrator
)
VALUES
( #{id},
#{username,jdbcType=VARCHAR},
#{password.encrypted:VARCHAR},
#{administrator,jdbcType=BOOLEAN}
)
</insert>

<update id="update" parameterType="UserAlias">
UPDATE user SET
username = #{username,jdbcType=VARCHAR},
password = #{password.encrypted,jdbcType=VARCHAR},
administrator = #{administrator,jdbcType=BOOLEAN}
WHERE
id = #{id,jdbcType=INTEGER}
</update>

<!-- Unique constraint check -->
<select id="isUniqueUsername" parameterType="map" resultType="boolean">
SELECT (count(*) = 0)
FROM user
WHERE ((#{userId,jdbcType=BIGINT} IS NOT NULL AND id != #{userId,jdbcType=BIGINT}) OR #{userId,jdbcType=BIGINT} IS
NULL) <!-- other than me -->
AND (username = #{username,jdbcType=VARCHAR})
</select>
</mapper>

第四、获取工具类,并打开sqlsession,来执行语句 如下:SqlSession sqlSession = sqlSessionFactory.openSession();
try {
//Create User
User user = new User();
user.setId(500000L);
user.setPassword(new EncryptedString("secret"));
user.setUsername("johnny" + Calendar.getInstance().getTimeInMillis());//random
user.setAdministrator(true);

sqlSession.insert(" User.insert", user);//注:User.insert :User是命名空间.id名,

//Retrieve User
user = (User) sqlSession.selectOne("User.find", user.getId());

assertNotNull(user.getId());

sqlSession.rollback();
} finally {
sqlSession.close();
}
}

注: 以下是例子参考:删除多条数据,以及删除单挑数据,用到的参数类型,
<?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">
<mapper namespace="Student">
<resultMap type="Student" id="students">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="name" jdbcType="VARCHAR" property="name"/>
<result column="age" jdbcType="INTEGER" property="age"/>
</resultMap>
<insert id="add" parameterType="Student">
insert into t_student values(null,#{name},#{age})
</insert>
<delete id="delete" parameterType="int">
delete from t_student where id=#{isisis} 单挑语句的删除其中#{sisiis}是基本类类型、名字任意,主要见名知意
</delete>
<delete id="deletes" parameterType="java.util.List">
delete from t_student where id in(
<foreach collection="list" item="item" separator=",">
#{item} 这个是多条语句的删除、parameterType="java.util.List" 其参数类型为list,返回多个、也就是对象,不是基本类型 separator=","是分割,,这的意思是以,逗号隔开,就看用在什么地方
</foreach>

)
</delete>
</mapper>
如下:参考图


第四、常用标签如下.
<select>标签中的<where>标签相当于select语句中的where条件
select * from where 1=1; <where>标签相当于where条件语句
如图:

注: 在<where>标签中有if标签
其中if标签中的语句拼接:解释如下:
假如如图上所示:两个条件都满足:语句如下
select * from message where and COMMAND=#{command} and DESCRIPTION like '%'#{description}'%'
那么<where>标签条件另外的一个作用就是把多余的那个and或者 or 给去掉 变成正确的sql语句:
select * from message where COMMAND=#{command} and DESCRIPTION like '%'#{description}'%'
2、<sql>标签 注: 当重复字段多了,用<sql>标签进行维护,去掉重复的
<sql>标签是去<select> 等其他标签评级的。写在<select>标签外,他就相当于java中常量定义的一样。
例如: 在java中 定义一个 java成员变量,其中成员变量已经赋初始的值,然后供应本类方法调用,其<sql>标签也是这个意思,把对应数据库的字段属性,先写好,那个<select>标签或者<delete>标签等、用到时直接引用 即可;
例子如下:
已经声明字段,并起名称id为 coumms
<sql id="columms"> ID、COMMAND、DESCRTION、COMTENT </sql>
引用如下:
如在<select>标签中
<select id="version" parameterType="long" resultType="int">
SELECT <include refid="columms"/> FROM user WHERE id = #{id,jdbcType=INTEGER}
</select>
3、<set>标签的使用,跟<where>标签是类似的;
例如:set语句就是<set>标签
<update id="update">
update MESSAGE
<set>
<if test="command!=null">
COMMAND=#{command},
</if>
<if test="description!=null">
DESCRIPTION=#{command} , 注: 用<set>标签他会帮你去掉 ,变成能够正常执行的sql语句和where标签一样都是 优化维护sql语句的,让用户方便使用
</if>
</set>
</update>

4、多对一,一对多
主表一的一方,能够查询出附表多的一方的数据,在<resultMap>标签中配置
如:
<collection property="contentlist" resutMap="CommandContent.Content"/>
property="contentlist" 是在一的一方 建立的list集合,并设置了get/set方法、把他引入
resutMap="CommandContent.Content"他就是多的一方的xml配置文件中的 namespace="CommandContent "点 <resultMap>中的id名称,也就是告诉一的一方的主表,多的一方配置的对应的字段数据在那,有多少子数据
如图所示:
2、 多对一、也就是在多的一放子表可以看到主表中的数据、
例如需求:当查询出子表中的数据,希望关联到主表,在子表对象里面能够看到主表对象里的内容那这个时候得需要用<association>标签
注: 在子表多的一方<resultMap>标签中配置:
例如:<association property="" resutMap="Command .Command"/>
property=""在子表的实体模型类中,设置主表对象的引用如:private Command command
resutMap="Command .Command" 和上面的一对多的配置一样、对应着主表中namespace.resultMap中的id
3、 以下是整个文档所用到的关键字:如下:


4、下面是插入数据<insert>表标签,
在实现插入数据时 获取插入数据的那个主键ID
如图:
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="student">
insert into student (id,name) values(1,'admin')
</insert>
useGeneratedKeys="true" keyProperty="id":他们是联合使用的、当你把useGeneratedKeys="true" 设置true时,就是获取当前插入成功数据的ID, keyProperty="id"就是把获取的当前数据的id,存到student类中的id中,
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值