1.输入映射和输出映射
Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心
UserMapper.xml文件中的配置:select标签(parameterType,resultType,resultMap),if、sql、where、foreach标签
1>parameterType:传入参数类型
简单类型:Integer,String....使用#{}占位符,或者${}进行sql拼接。
pojo对象:User对象,Orders对象.....使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称
QueryVo包装对象(User为QueryVo的属性):
<!-- 根据vo查
public List<User> findByVo(QueryVo vo); -->
<select id="findByVo" parameterType="QueryVo" resultType="User">
select * from user where username = #{user.username}
</select>
2>resultType:输出参数类型
简单类型:Integer,String...
pojo对象:User对象,Orders对象.....
3>resultMap:自动封装输出参数
<!--当pojo中的属性名与数据库列名不对应时,我们使用resultMap手动映射,只封装我们想要(name不同)的属性即可 -->
<!-- id:设置主键
property:主键在pojo中的属性名
column:主键在数据库中的列名 -->
<resultMap type="Orders" id="texOrders">
<result column="user_id" property="userId"/>
</resultMap>
<!-- 查询订单表order的所有数据
public List<Orders> findAll() -->
<select id="findAll" resultMap="texOrders" >
select * from orders
</select>
2.动态SQL
if、sql、where、foreach标签
1>sql:相同sql的抽取(如:select * from user)
<!-- sql片段抽取 -->
<sql id="texSql">
select * from user
</sql>
<select id="findByIds" resultType="User">
<include refid="texSql"/>
</select>
2>if:查询前先进行判断
<!-- 根据性别和名字查询用户
public List<User> findByUsernameANDSex(User user); -->
<select id="findByUsernameANDSex" parameterType="User" resultType="user">
<if test="username != null and username != ''">
AND username = #{username}
</if>
<if test="sex != null and sex != ''">
AND sex = #{sex}
</if>
</select>
3>where:去掉前and(不能去掉后and)
<!-- 根据性别和名字查询用户
public List<User> findByUsernameANDSex(User user); -->
<select id="findByUsernameANDSex" parameterType="User" resultType="user">
<include refid="texSql"/>
<where>
<if test="username != null and username != ''">
AND username = #{username}
</if>
<if test="sex != null and sex != ''">
AND sex = #{sex}
</if>
</where>
</select>
4>foreach:循环遍历(
当传入的是QueryVo时,foreach中的collection值直接写QueryVo中的属性名即可,
当传入的是Integer[]类型时,mybatis会将传入名改变为array,所以collection值填写array
当传入的是List<Integer>类型时,mybatis会将传入名改变为list,所以collection值填写list
)
<!-- //根据ids查询用户
List<User> findByIds(QueryVo ids);
List<User> findByIds2(Integer[] ids);//array
List<User> findByIds3(List<Integer> ids);//list -->
<select id="findByIds" parameterType="QueryVo" resultType="User">
<include refid="texSql"/>
<where>
id in
<foreach collection="idsList" item="ids" open="(" close=")" separator=",">
#{ids}
</foreach>
</where>
</select>
<select id="findByIds2" parameterType="Integer" resultType="User">
<include refid="texSql"/>
<where>
id in
<foreach collection="array" item="ids" open="(" close=")" separator=",">
#{ids}
</foreach>
</where>
</select>
<select id="findByIds3" parameterType="Integer" resultType="User">
<include refid="texSql"/>
<where>
id in
<foreach collection="list" item="ids" open="(" close=")" separator=",">
#{ids}
</foreach>
</where>
</select>
3.关联查询(划重点)
一对一:一个订单只能由一个用户创建,一对多:一个用户可以创建多个订单
一对一查询:使用resultMap中的association
1>在orders表中声明user
//表达一对一
private User user;get/set
2>OrdersMapper.xml映射文件中表达
<!-- //表达一对一关系
public List<Orders> findByOneToOne(); -->
<resultMap type="Orders" id="resOrder">
<id column="id" property="id"/>
<result column="number" property="number"/>
<!-- 一对一关系内部表达 -->
<association property="user" javaType="User">
<id column="user_id" property="id"/>
<result column="username" property="username"/>
</association>
</resultMap>
<select id="findByOneToOne" resultMap="resOrder">
SELECT
o.id,
o.number,
o.user_id,
u.username
FROM
orders o LEFT JOIN USER u
ON o.user_id = u.id
</select>
一对多查询:使用resultMap中的association
1>在User中声明List<Orders>
//表达一对多关系
private List<Orders> ordList;get/set
2>UserMapper.xml映射文件中表达
<!-- //表达多对多关系
public User findByMoreToMore(); -->
<resultMap type="User" id="resUser">
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<!-- 表达多对多关系 -->
<collection property="ordList" ofType="Orders">
<id column="id" property="id"/>
<result column="number" property="number"/>
</collection>
</resultMap>
<select id="findByMoreToMore" resultMap="resUser">
SELECT
o.id,
o.number,
o.user_id,
u.username
FROM USER u LEFT JOIN orders o
ON o.user_id = u.id
</select>
4.mybatis与spring的整合(划重点)
1>整合思路
SqlSessionFactory对象应该放到spring容器中作为单例存在。
Mapper代理形式中,应该从spring容器中直接获得mapper的代理对象。
数据库的连接以及数据库连接池事务管理都交给spring容器来完成
2>所需jar包
spring的jar包、Mybatis的jar包、Spring+mybatis的整合包、mysql数据库驱动包、连接池包
3>applciationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置mybatis核心配置文件 -->
<property name="configLocation" value="sqlMapConfig.xml" />
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Mapper动态代理开发
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
<property name="mapperInterface" value="com.imwj.mapper.UserMapper"/>
</bean> -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 路径基本包 -->
<property name="basePackage" value="com.imwj.mapper"/>
</bean>
</beans>
db.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
4>sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<!-- 2. 指定扫描包,会把包内所有的类都设置别名,别名的名称就是类名,大小写不敏感 -->
<package name="com.imwj.pojo" />
</typeAliases>
<mappers>
<!-- 扫描整个包路径 -->
<package name="com.imwj.mapper"/>
</mappers>
</configuration>
5>UserMapper.xml
<?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">
<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="com.imwj.mapper.UserMapper">
<!-- 根据id查询 -->
<select id="findById" parameterType="Integer" resultType="User">
select * from user where id = #{id}
</select>
</mapper>
6>UserMapper.java
public interface UserMapper {
//根据id查询
public User findById(Integer id);
7>测试
@Test
public void fun2(){
ClassPathXmlApplicationContext apx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserMapper mapper = (UserMapper) apx.getBean("userMapper");
User user = mapper.findById(1);
System.out.println(user);
}
6.逆向工程
简单点说,就是通过数据库中的单表,自动生成java代码。
Mybatis官方提供了逆向工程,可以针对单表自动生成mybatis代码(mapper.java\mapper.xml\po类)
2>生成文件
3>使用
@Test
public void fun1(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserMapper userMapper = ac.getBean(UserMapper.class);
UserExample userExample = new UserExample();
userExample.createCriteria().andUsernameLike("%张%");
List<User> users = userMapper.selectByExample(userExample);
for (User user : users) {
System.out.println(user);
}
}