Mybatis的使用:
前面我们已经介绍了SSM框架的整合,下面介绍下Mybatis的使用:
1.首先介绍下xml方式入门:
1.Dao接口:和之前SSM整合一样,使用Mybatis需要Dao接口:
Repository
public interface UserDao {
public List<User> findAll();
}
2.Dao映射文件:注意Dao映射文件的路径在resources下,同时包名路径要和Dao接口保持一致:
<?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: 必须写Dao接口的全限定类名-->
<mapper namespace="com.it.dao.UserDao">
<!--查询用select标签,id:Dao接口中的方法名, resultType:返回结果类型,如果是集合,写集合的泛型-->
<select id="findAll" resultType="User">
SELECT * FROM t_user
</select>
</mapper>
3.Spring整合mybatis的配置文件:applicationContext.xml:
在这个配置文件中,主要配置:
1.数据源DataSource;
2.SqlSessionFactoryBean;
3.Dao接口映射文件:
可以直接批量导入,注意Dao接口映射文件要和Dao接口包名路径一致;
也可以通过导入其他配置文件,在其他配置文件中配置Dao接口映射文件;
4.Pojo配置别名;
5.Dao接口扫描批量配置:指定接口所在的包名;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--数据源-->
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_day01"/>
</bean>
<!--spring和mybatis整合的工厂bean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--引入其他配置文件:sqlMapConfig.xml-->
<!-- <property name="configLocation" value="classpath:sqlMapConfig.xml" />-->
<!--批量引入Dao接口映射文件-->
<property name="mapperLocations" value="classpath:com/it/dao/*.xml"></property>
<!--配置别名-->
<property name="typeAliasesPackage" value="com.it.pojo"></property>
</bean>
<!--批量扫描接口生成代理对象,让Dao的接口被spring管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定接口所在的包-->
<property name="basePackage" value="com.it.dao"/>
</bean>
</beans>
4.springmvc配置文件:springmvc.xml
主要配置:
组件扫描;
注解驱动;
视图解析器;
静态资源过滤;
导入其他配置文件:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--一:spring整合mvc,使用@Controller或者@RestController-->
<!--组件扫描-->
<context:component-scan base-package="com.it"></context:component-scan>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置注解驱动支持-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 设置静态资源不过滤 -->
<mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
<mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
<mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->
<import resource="classpath:applicationContext.xml"></import>
<!--<import resource="classpath:sqlMapConfig.xml"></import>-->
</beans>
5.web.xml文件配置:前端控制器和编码过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- 解决post乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定加载的配置文件 ,通过参数contextConfigLocation加载 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.Dao接口映射文件详细介绍:
1.简单的增删改查(可以使用通用Mapper,使用通用Mapper可以不需要配置文件)
<?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: 必须写Dao接口的全限定类名-->
<mapper namespace="com.it.dao.UserDao">
<!--查询用select标签,id:Dao接口中的方法名, resultType:返回结果类型,如果是集合,写集合的泛型
可以直接写User是因为已经配置了POJO别名-->
<select id="findAll" resultType="User">
SELECT * FROM t_user
</select>
<!--新增用insert标签,parameterType指定方法的参数类型-->
<insert id="save" parameterType="User">
INSERT INTO t_user(username,sex,birthday,address) VALUES (#{username},#{sex},#{birthday},#{address})
</insert>
<!--修改使用update标签-->
<update id="update" parameterType="User">
UPDATE t_user SET username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} WHERE uid=#{uid}
</update>
<!--删除使用delete标签,参数类型id为int-->
<delete id="delete" parameterType="int">
DELETE FROM t_user WHERE uid = #{uid}
</delete>
</mapper>
2.parameterType深入:
1.Dao接口的方法参数是简单类型:
直接写`#{任意字段}`或者`${value}`,例如: #{uid}
2.传递 pojo 对象:
使用 ognl 表达式解析对象字段的值, #{}或者${}括号中的值为 pojo 属性名称。例如:#{username},#{sex};
3.传递 pojo 包装对象类型 :
例如,在畅购中,Goods里面包装了Spu和List<Sku>,在这种情况下:先将Goods里面的pojo当做属性,先获取spu,再获取spu里面的属性;
例如:parameterType="Goods"
获取:#{spu.id}
3.resultType深入:
1.返回简单类型:Dao接口方法中返回值为int类型
例如:resultType="int"
2.返回POJO类型:
例如:resultType="User"
3.返回集合类型:Dao接口中的方法返回值为集合类型List<User>
例如:resultType="User", User是集合中的泛型
4.resulrMap:
当MySQL查询出来的结果中的数据列名和Pojo属性不一致时,resultType是无法进行封装的,此时需要使用resultMap;
例如数据库中的列名是_uid,_username,Pojo中是uid,username;这种情况使用resultType无法封装,需要使用resultMap;
id="findAllMap",唯一标识,下面select中的一致即可;
type="User",与Dao接口中的方法返回值一致;
<id property="uid" column="_uid"></id>:映射主键,property指定pojo中属性名,column指定MySQL中查询结果中的列名;
<result property="username" column="_username"></result>:除了主键,其余都用resultMap;
<resultMap id="findAllMap" type="User">
<id property="uid" column="_uid"></id>
<result property="username" column="_username"></result>
<result property="birthday" column="_birthday"></result>
<result property="sex" column="_sex"></result>
<result property="address" column="_address"></result>
</resultMap>
<select id="findAll" resultMap="findAllMap">
SELECT * FROM t_user2
</select>
3.动态sql标签:
1.if标签判断,一般和where标签一起用:
<!--如果用户id不为空,根据id查询;
如果用户姓名不为空,根据用户姓名查询
如果两者都不为空,并列条件查询
如果都为空查询所有-->
<select id="findByQueryVo" parameterType="QueryVo" resultType="User">
SELECT uid, username, address FROM t_user
<where>
<if test="user!=null and user.uid!=0">
AND uid>#{user.uid}
</if>
<if test="user!=null and user.username!=null and user.username!=''">
AND username like #{user.username}
</if>
</where>
</select>
2.foreach标签:遍历集合,获取集合中的值
<select id="findRange" parameterType="QueryVo" resultType="User">
SELECT uid, username, address FROM t_user
<where>
<if test="user!=null and user.username!=null and user.username.length>0">
AND username like #{user.username}
</if>
<if test="ids!=null">
<!--collection:指定要遍历的集合名,
open:语句的开始,
item:每次遍历的赋值变量
separator:item和item之间的分割
close:语句的结束
实质是拼接成:AND (uid =1 OR uid =2 OR uid=6)
或者使用AND uid IN (1,7,10,18)也可以-->
<!-- <foreach collection="ids" item="id" open="AND (uid=" close=")" separator="OR uid=">
#{id}
</foreach>-->
<foreach collection="ids" item="id" open="uid IN (" close=")" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
4.多表关联查询:
1.一(多)对一的情况:一个账户对应一个用户
一个账户对应一个用户:查询账户关联用户,可以在账户的pojo中将用户pojo作为属性;
在xml中使用association进行关联;
1.在Account中将User当做属性:
private User user;//一个账户对应一个用户
2.使用association进行关联:
<resultMap id="findAccountListMap" type="Account">
<id property="aid" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--一对一关联使用association-->
<association property="user" javaType="User">
<result property="username" column="username"></result>
<result property="address" column="address"></result>
</association>
</resultMap>
<select id="findAccountList" resultMap="findAccountListMap">
SELECT a.*,u.username,u.address FROM t_account a, t_user u where a.uid=u.uid;
</select>
2.一对多的情况:一个用户有多个账户:
1.在用户POJO中注入集合属性,泛型为账户;
private List<Account> accounts;
2.使用collection进行关联:
<select id="findUserAccountList" resultMap="userAccountListMap">
SELECT u.*,a.aid, a.money FROM t_user u LEFT OUTER JOIN t_account a ON u.uid=a.uid
</select>
<resultMap id="userAccountListMap" type="User">
<id property="uid" column="uid"></id>
<result property="username" column="username"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<result property="address" column="address"></result>
<!--加载多方数据,property属性:一方类里面List集合的属性名; ofType:List中的对象类型-->
<collection property="accounts" ofType="Account">
<result property="aid" column="aid"></result>
<result property="money" column="money"></result>
</collection>
</resultMap>
3.多对多的情况:例如:一个用户有多个角色,一个角色可以对应多个用户;
多对多可以看成是两个一对多:
1.一个角色对应多个用户:
在角色pojo(Role)中,将用户集合当做属性:
private List<User> users;
2.使用collection进行关联:
<select id="findRoleList" resultMap="roleListMap">
SELECT r.*, u.uid, u.username,u.sex,u.birthday,u.address FROM t_role r, user_role ur, t_user u
WHERE r.rid = ur.rid AND ur.uid = u.uid
</select>
<resultMap id="roleListMap" type="Role">
<id column="rid" property="rid"></id>
<result column="rName" property="rName"></result>
<result column="rDesc" property="rDesc"></result>
<collection property="users" ofType="User">
<result property="username" column="username"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<result property="address" column="address"></result>
</collection>
</resultMap>