一.MyBatis的ORM映射
为什么有ORM映射
MyBatis只能自动维护库表"列名"与"属性名"相同的关系,二者不同时无法找到ORM
理解:当库表列名带"_"下划线时自动ORM映射失效
方法一:
在SQL语句中使用as为查询字段添加别名以匹配属性名
<select id="findAll" resultType="com.by.pojo.Role" >
select id, role_name as roleName, role_desc as roleDesc from role
</select>
方法二:结果映射
使用ResultMap
标签手动映射,解决实体字段和数据表字段不一致的问题
<!--
id:和select查询标签的返回值保持一致
type: 映射实体的全类名
-->
<resultMap id="findAll2ResultMap" type="com.by.pojo.Role">
<!--
描述主键字段的映射关系:
property:实体类的属性
column:数据表字段名称
-->
<id property="id" column="id" />
<!--
描述非主键字段的映射关系:
property:实体类的属性
column:数据表字段名称
-->
<result property="roleName" column="role_name" />
<result property="roleDesc" column="role_desc" />
</resultMap>
<select id="findAll2" resultMap="findAll2ResultMap" >
select * from role
</select>
二.
.MyBatis的配置文件
1.
properties标签
1.一般会把数据库配置信息定义在一个独立的配置文件里面,比如
db.properties:(SQl8.0版本)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/sys?characterEncoding=UTF-8
username=root
password=123456
2.在SqlMapConfig.xml引入数据库配置信息
<configuration>
<!--引入db.properties-->
<properties resource="db.properties"></properties>
2.typeAliases标签
实体类定义别名,提高书写效率:
<typeAliases>
<!--定义单个别名-->
<!--<typeAlias type="com.by.pojo.User" alias="User"></typeAlias>-->
<!--批量定义别名-->
<package name="com.by.pojo"></package>
</typeAliases>
使用别名:使用基本数据类型,自定义对象使用对象名即可
3.Mappers标签
Mappers标签的作用是用来在核心配置文件里面引入映射文件
1.使用mapper映射文件的路径
<mappers>
<mapper resource="com/by/dao/UserDao.xml"/>
</mappers>
2.使用mapper接口的路径
<mappers>
<mapper class="com.by.dao.UserDao"></mapper>
</mappers>
3.使用mapper接口的包名批量引入
<mappers>
<package name="com.by.dao"></package>
</mappers>
三.
MyBatis的关联查询----一对一查询
在SQL中连接为:
select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id
public class Account implements Serializable {
private Integer id;
private Integer uid;
private Double money;
//加入User类的对象作为Account类的一个属性
private User user;
使用映射与 association,分别接收数据
<?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="com.by.dao.AccountDao">
<!-- 结果映射 -->
<resultMap type="account" id="findAllResultMap">
<id column="aid" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!-- 指定关系表中数据的封装规则 -->
<association property="user" javaType="user">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findAll" resultMap="findAllResultMap">
select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id
</select>
</mapper>