1>查询所有操作
<!--配置查询所有--><selectid="fingetUser"resultType="cn.mybatis.domain.User">
select * from user;
</select>
2>添加信息操作
<!--保存用户--><insertid="saveUser"parameterType="cn.mybatis.domain.User">
insert into user(username,address,sex,birthday)values (#{username},#{address},#{sex},#{birthday});
</insert>
3>更改信息操作
<!--更新用户--><updateid="updateUser"parameterType="cn.mybatis.domain.User">
update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday}
where id=#{id};
</update>
4>删除信息操作
<!--删除用户--><deleteid="deleteUser"parameterType="java.lang.Integer">
delete from user where id=#{userid};
</delete>
5>根据单个信息来查询数据
<!--根据id查询用户--><!--同时需要返回结果集需要告诉返回值是什么类型--><selectid="getUserByid"parameterType="java.lang.Integer"resultType="cn.mybatis.domain.User">
select * from user where id=#{userid};
</select>
6>模糊查询的操作
注意:要在调用该方法的时候添加% %
<!--使用模糊查询查询到用户的数据--><selectid="getUserbyname"parameterType="String"resultType="cn.mybatis.domain.User">
select * from user where username like #{name};
</select>
7>使用聚合函数查询记录的总数
<!--使用聚合函数count查询user表中的用户数据--><selectid="userCount"resultType="int">
select count(id)from user;
</select>
注意:
select * from user where username like '%${value}%';
执行的Sql语句是 select * from user where username like'%王%'(使用的是Statement的拼接S ql)
select *from user where username like #{name};
执行的Sql语句是 select * from user where username like ?;(使用的是prepateStatement的占位符)
8>在插入操作之前的到添加数据的编号
<!--配置插入操作后获取插入数据的返回值id--><!-- keyProperty:实体类名称 order:执行顺序 resultType:返回类型--><selectKeykeyProperty="id"order="AFTER"resultType="java.lang.Integer">
select last_insert_id();
</selectKey>
9>#{}和${}的区别
#{}表示一个占位符号
通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转化#{}可以有效的防止Sql注入,#{}可以接收简单类型值或pojo属性值,如果paremeterType传输单个简单类型值,#{}括号中可以是value或是其他值
${}表示拼接字符串
通过${}可以将paramererType传入的内容拼接在Sql中且不进行jdbc类型转换,${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value
注:源码中指定了读取的key的名字就是value所以我们就只能叫做value
在实体类名和数据名不同的时候怎么操作
1>在配置数据库文件的时候更改Sql语句(执行效率更快)
select * from user where username as userName;
2>在配置数据库文件中添加对应关系(执行顺序相对慢)
<!--配置查询结果的列名和实体列属性的对应关系--><resultMapid="userMap"type="cn.mybatis.domain.User"><!--主键字段的对应--><idproperty="userid"column="id"></id><!--非主键字段的对应--><resultproperty="userName"column="username"></result><resultproperty="userAddress"column="address"></result><resultproperty="userSex"column="sex"></result><resultproperty="userBirthday"column="birthday"></result></resultMap>
在需要调用的属性添加resultMap="userMap";
1>
动态SQLMyBatis最强大的特性之一一直是它的动态SQL功能。如果您有使用JDBC或任何类似框架的经验,就会理解有条件地将SQL字符串连接在一起是多么痛苦,请确保不要忘记空格或忽略列列表末尾的omma。处理动态SQL可能非常困难。虽然使用动态SQL永远不会有什么好处,但是MyBatis使用了一种强大的动态SQL语言,可以2>2>
在任何映射的SQL语句中使用,这无疑改善了这种情况。
3>
使用过JSTL或任何类似的基于XML的文本处理器的人都应该熟悉动态SQL元素。在MyBatis的早期版本中,有很多需要了解和理解的元素。MyBatis大大改进了这一点,现在只有不到一半的元素。处理。MyBatis使用强大的基于OGNL的表达式来消除大部分其他元素:ifchoose(when,otherwise)trim(where,set)
foreach
4>动态Sql之<if>标签
<select id="findByUser" resultType="user" parameterType="user">
select * from user where1=1<if test="username!=null and username!=''">
and username like #{username}<if test="address!=null">
and address like #{username}</select>
注意:<if>标签的test属性中写的是对象的属性名,如果包装类的对象要使用OGNL表达式的写法另外要注意where 1=1的作用(使条件为真)5>动态标签之<where>标签
为了简便上面 where 1=1的操作我们可以使用where来简便
扩展:抽取查询语句中的重复语句:最终达到Sql可以重用的作用
<!--抽取重复的Sql语句--><sql id="defaultUser">
select * from user
</sql><select id="findByUser" resultType="user" parameterType="user"><include refid="defaultUser"></include><where><if test="username!=null and username!=''">
and username like #{username}<if test="address!=null">
and address like #{username}<where></select>
注意:在编写Sql的时候尽量不要去加分号
/*The error may exist in com/itxu/Dao/IUserDao.xml
### The error may involve cn.mybatis.Dao.IUserDao.findUserInIds-Inline
### The error occurred while setting parameters
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ';*/6>动态标签之<foreach>标签
当需求发生改变:
传入多个 id 查询用户信息,用下边两个 sql 实现:
SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16) SELECT * FROM USERS WHERE username LIKE '%张%' AND id IN (10,89,16)
这样我们在进行范围查询时,就要将一个集合中的值,作为参数动态添加进来。 这样我们将如何进行参数的传递?
持久层Dao映射配置的编写:<!--查询所在用户的id集合--><select id="findInids" resultType="user" parametrType="cn.mybatis.domian.QueryVo"><!--select * from user where id in(1,2,3,4)--><include refid="defaultUser"></include><where><if text="ids!=null and ids.size()>0"></if><foreach collection="ids" open="id in(" close=")" item="uid" separator=",">
#{uid}</foreach></where></select>
Sql语句:select * from user where id in(?);<foreach>标签用于遍历集合他们的属性分别是:
collection:代表要遍历的集合元素,注意编写的时候不要写${}
open:代表语句的开始部分
close:代表语句的结束部分
item:代表遍历集合的每个元素生成的变量名
separator:代表分隔符
9.Mybatis中的多表查询
1>表之间的关系有几种
一对多
多对一
一对一
多对多
举例:
用户和订单就是(一对多)
一个用户可以下多个订单/多个订单属于同一个用户
人和身份证就是(一对一)
一个人只能有一个身份证号/一个身份证号只能有一个人
学生和老师就是(多对多)
一个学生可以被多个老师教过/一个老师可以教多个学生
特例:
如果拿出每一个订单/他都只能属于一个用户所以Mybatis中就把多对一看成了一对一
mybatis中的多表查询:
一个用户可以有多个账户/一个账户只能属于一个用户(多个账户也可以属于同一个用户)
步骤:1.建立两张表:用户表和账户表
让用户表和账户表之间具备一对多的关系:需要使用外键在账户表中添加
2.建立两个实体类:用户实体类和账户实体类
让用户和账户的实体类能体现出一对多的关系
3.建立两个配置文件
4.实现配置:
当我们查询用户时可以同时得到用户下所包含的账户信息
当我们查询账户时,可以同时得到账户的所属用户信息
实现多对多关系的案例:1.建立两张表:用户表,角色表
让用户和角色表具有多对多关系,需要使用中间表,中间表中包含各自的主键,在中间表是外键
2.建立两个实体类:用户实体类和角色实体类
让用户和角色的实体能体现出来多对多的关系
各自包含对方一个集合引用
3.建立两个配置文件
用户的配置文件
角色的配置文件
4.实现配置
当我们查询用户的时候,可以同时得到用户所包含的角色信息
当我们查询角色的时候,可以同时得到角色的所赋予的用户信息
2>.一对一关系
//从表实体应该包含主表实体的对象引用private User user;
并且需要编写配置文件
<resultMap id="accountUserMap" type="cn.mybatis.domain.Account"><id property="id" column="aid"></id><result property="uid" column="uid"></result><result property="money" column="money"></result><!--一对一的关系映射--><association property="user" column="uid" javaType="User"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result></association></resultMap>
SQL: select a.*,u.username,u.address from account a,user u where u.id=a.uid;3>.一对多关系
//主体表中应该包含从表的集合private List<Account> accounts;
并且需要编写配置文件
<!--定义User的ResultMap--><resultMap id="userAccountMap" type="user"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result><!--配置User对象中account集合的映射--><collection property="accounts" ofType="Account"><id property="id" column="id"></id><result property="uid" column="uid"></result><result property="money" column="money"></result></collection></resultMap>
Sql: SELECT * from user u LEFT OUTER JOIN account a on u.id=a.uid;4>多对多关系
//通过中间表建立关系分别在主表和从表中添加相应的集合private List<User>users;private List<Role>roles;<!--在双方的配置文件配置对应得ResultMap和collection-->
IUserDao.xml
<resultMap id="UserRoleMap" type="user"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result><collection property="roles" ofType="role">//定义集合<id property="roleid" column="id"></id><result column="role_name" property="rolename"></result><result column="role_desc" property="roledesc"></result></collection></resultMap>
IRoleDao.xml<和mapper同><resultMap id="RoleMap" type="role"><id property="roleid" column="id"></id><result property="rolename" column="role_name"></result><result property="roledesc" column="role_desc"></result><collection property="users" ofType="user"><id property="id" column="id"></id><result property="username" column="username"></result><result property="address" column="address"></result><result property="sex" column="sex"></result><result property="birthday" column="birthday"></result></collection></resultMap>
Sql: select u.*,r.ROLE_NAME,r.ROLE_DESC from role r LEFT OUTER JOIN user_role ur on r.ID=ur.RID
LEFT OUTER JOIN user u on u.id=ur.uid;
双左联双查询条件
>>M共有四种注解方式
@SELECT@UPDATE@INSERT@DELETE1>查询所有
@Select("select * from user")2>添加数据
@INSERT("INSERT INTO USER(username,address,sex,birthday) VALUES(#{username},#{address},#{sex},#{birthday})")3>修改数据
@UPDATE("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}")4>删除数据
@DELETE("delete from user where id=#{id}")5>查询一个用户
@Select("select * from user where id=#{id}")6>模糊查询
@Select("select * from user where username like #{username}")@Select("select * from user where username like '%${value}%'")7>实体类名与数据库名不相同的解决方案
@Results(id ="userMap",value ={@Result(id=true,column ="id",property ="userId"),@Result(column ="username",property ="userName"),@Result(column ="address",property ="userAddress"),@Result(column ="sex",property ="userSex"),@Result(column ="birthday",property ="userBirthday"),})@ResultMap(value={"userMap"})//引用上边的注解8>Mybatis基于注解开发的一对多或者是多对一的注解配置
一:@Result(property ="user",column ="uid",one=@One(select="cn.mybatis.Dao.UserDao.findUserByid",fetchType= FetchType.EAGER))
多:@Result(property ="accounts",column ="id",
many =@Many(select ="cn.mybatis.Dao.AccountDao.findUserByuid",
fetchType = FetchType.LAZY))9>Mybatis基于注解开发配置二级缓存