mybatis.zzh
Mybatis介绍:
JDBC的缺点
Mybatis架构
Mybatis环境搭建
SqlMapConfig的配置
<?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><!-- 和spring整合后 environments配置将废除 --><environments default="development"><environment id="development"><!-- 使用jdbc事务管理 --><transactionManager type="JDBC" /><!-- 数据库连接池 --><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url"value="jdbc:mysql:///mybatis?characterEncoding=utf-8" /><property name="username" value="root" /><property name="password" value="123" /></dataSource></environment></environments><mappers><!-- <mapper resource="com/zzh/mapper/User.xml"/> --><!-- 建议使用package这种情况下,接口名需要与对应的mapper.xml文件名一致 --><package name="com.zzh.dao"/></mappers>
</configuration>
<?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>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql:///mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- <mapper resource="com/zzh/mapper/User.xml"/> -->
<!-- 建议使用package
这种情况下,接口名需要与对应的mapper.xml文件名一致
-->
<package name="com.zzh.dao"/>
</mappers>
</configuration>
Mapper.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="test"><!-- id:statement的id 或者叫做sql的id--><!-- parameterType:声明输入参数的类型 --><!-- resultType:声明输出结果的类型,应该填写pojo的全路径 --><!-- #{}:输入参数的占位符,相当于jdbc的? --><select id="queryUserById" parameterType="int" resultType="com.zzh.bean.User">SELECT * FROM `user` WHERE id = #{id}</select><!-- 根据用户名模糊查询用户列表#{} SELECT * FROM `user` WHERE id = ? 占位符 ? == '字符串'${} SELECT * FROM `user` WHERE username like '%字符串%'--><select id="findUserByUsername" parameterType="String"resultType="com.zzh.bean.User">select * from user where username like "%"#{value}"%"</select><insert id="insertUser" parameterType="com.zzh.bean.User"><selectKey keyProperty="id" resultType="Integer" order="AFTER">select LAST_INSERT_ID()</selectKey>insert into user (username,sex,birthday,address) values (#{username},#{sex},#{birthday},#{address})</insert><update id="updateUserById" parameterType="com.zzh.bean.User" >update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address}where id = #{id}</update><delete id="deleteUserById" parameterType="Integer">delete from user where id=#{id}</delete></mapper>
x
<?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="test">
<!-- id:statement的id 或者叫做sql的id-->
<!-- parameterType:声明输入参数的类型 -->
<!-- resultType:声明输出结果的类型,应该填写pojo的全路径 -->
<!-- #{}:输入参数的占位符,相当于jdbc的? -->
<select id="queryUserById" parameterType="int" resultType="com.zzh.bean.User">
SELECT * FROM `user` WHERE id = #{id}
</select>
<!-- 根据用户名模糊查询用户列表
#{} SELECT * FROM `user` WHERE id = ? 占位符 ? == '字符串'
${} SELECT * FROM `user` WHERE username like '%字符串%'
-->
<select id="findUserByUsername" parameterType="String"
resultType="com.zzh.bean.User">
select * from user where username like "%"#{value}"%"
</select>
<insert id="insertUser" parameterType="com.zzh.bean.User">
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
insert into user (username,sex,birthday,address) values (#{username},#{sex},#{birthday},#{address})
</insert>
<update id="updateUserById" parameterType="com.zzh.bean.User" >
update user
set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address}
where id = #{id}
</update>
<delete id="deleteUserById" parameterType="Integer">
delete from user where id=#{id}
</delete>
</mapper>
在config下创建log4j.properties如下:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%nmybatis默认使用log4j作为输出日志信息。
在config下创建log4j.properties如下:
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
mybatis默认使用log4j作为输出日志信息。
小结
Hibernate和Mybatis的区别
Mybatis和hibernate不同,它不完全是一个ORM框架,因为MyBatis需要程序员自己编写Sql语句。mybatis可以通过XML或注解方式灵活配置要运行的sql语句,并将java对象和sql语句映射生成最终执行的sql,最后将sql执行的结果再映射生成java对象。
Mybatis学习门槛低,简单易学,程序员直接编写原生态sql,可严格控制sql执行性能,灵活度高,非常适合对关系数据模型要求不高的软件开发,例如互联网软件、企业运营类软件等,因为这类软件需求变化频繁,一但需求变化要求成果输出迅速。但是灵活的前提是mybatis无法做到数据库无关性,如果需要实现支持多种数据库的软件则需要自定义多套sql映射文件,工作量大。
Hibernate对象/关系映射能力强,数据库无关性好,对于关系模型要求高的软件(例如需求固定的定制化软件)如果用hibernate开发可以节省很多代码,提高效率。但是Hibernate的学习门槛高,要精通门槛更高,而且怎么设计O/R映射,在性能和对象模型之间如何权衡,以及怎样用好Hibernate需要具有很强的经验和能力才行。
Dao开发方法
1、SqlSession的适用范围
1.1、SqlSessionFactoryBuilder
1.2、SqlSessionFactory
1.3、SqlSession
2、原始Dao开发
原始Dao开发存在的问题
3、Mapper动态代理方式
3.1、开发规范
3.2、开发步骤
Mapper的动态代理方式的四大原则
SqlMapConfig.xml配置文件
配置内容
typeAliases(类型别名)
mappers(映射器)
创建POJO包装类
package com.zzh.bean;import java.io.Serializable;public class QueryVo implements Serializable{/*** */private static final long serialVersionUID = 1L;private User user;public User getUser() {return user;}public void setUser(User user) {this.user = user;}}
package com.zzh.bean;
import java.io.Serializable;
public class QueryVo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
配置ResultMap
<resultMap type="Orders" id="order"><result column="user_id" property="userId"/></resultMap>
<resultMap type="Orders" id="order">
<result column="user_id" property="userId"/>
</resultMap>
动态Sql
<if test="sex != null and sex != ''">AND sex = #{sex}</if><if test="username != null and username != ''">AND username LIKE'%${username}%'</if>
<if test="sex != null and sex != ''">
AND sex = #{sex}
</if>
<if test="username != null and username != ''">
AND username LIKE
'%${username}%'
</if>
<!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字 注意此时处理的第一个and是条件语句前的and--><where><if test="sex != null">AND sex = #{sex}</if><if test="username != null and username != ''">AND username LIKE'%${username}%'</if></where>
<!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字
注意此时处理的第一个and是条件语句前的and
-->
<where>
<if test="sex != null">
AND sex = #{sex}
</if>
<if test="username != null and username != ''">
AND username LIKE
'%${username}%'
</if>
</where>
<sql id="selector">select * from user</sql><select><include refid="selector"></include></select>
<sql id="selector">
select * from user
</sql>
<select>
<include refid="selector"></include>
</select>
<select id="queryUsersByIds" parameterType="QueryVo" resultType="User"><include refid="selector"></include><where><foreach collection="idsList" item="id" separator="," open="id in (" close=")">#{id}</foreach></where></select>
<select id="queryUsersByIds" parameterType="QueryVo" resultType="User">
<include refid="selector"></include>
<where>
<foreach collection="idsList" item="id" separator="," open="id in (" close=")">
#{id}
</foreach>
</where>
</select>
关联查询
一对一查询
使用resultMap
<!-- 一对一查询 --><resultMap type="Orders" id="oneToOne"><result column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><association property="user" javaType="user"><id column="id" property="id"/><result column="username" property="username"/></association></resultMap><select id="findOrders" resultMap="oneToOne">select o.id,o.user_id,o.number,o.createtime,u.id,u.username from orders o left join user uon o.user_id = u.id</select>
<!-- 一对一查询 -->
<resultMap type="Orders" id="oneToOne">
<result column="id" property="id"/>
<result column="user_id" property="userId"/>
<result column="number" property="number"/>
<association property="user" javaType="user">
<id column="id" property="id"/>
<result column="username" property="username"/>
</association>
</resultMap>
<select id="findOrders" resultMap="oneToOne">
select
o.id,
o.user_id,
o.number,
o.createtime,
u.id,
u.username
from orders o
left join user u
on o.user_id = u.id
</select>
一对多查询
<!-- 一对多查询 --><resultMap type="User" id="user"><id column="user_id" property="id"/><result column="username" property="username"/><collection property="orderList" ofType="Orders"><id column="id" property="id"/><result column="number" property="number"/><result column="user_id" property="userId"/><result column="createtime" property="createtime"/></collection></resultMap><select id="findUserList" resultMap="user">SELECT o.id,o.user_id,o.number,o.createtime,u.username FROM user u LEFT JOIN orders oON o.user_id = u.id</select>
<!-- 一对多查询 -->
<resultMap type="User" id="user">
<id column="user_id" property="id"/>
<result column="username" property="username"/>
<collection property="orderList" ofType="Orders">
<id column="id" property="id"/>
<result column="number" property="number"/>
<result column="user_id" property="userId"/>
<result column="createtime" property="createtime"/>
</collection>
</resultMap>
<select id="findUserList" resultMap="user">
SELECT
o.id,
o.user_id,
o.number,
o.createtime,
u.username
FROM user u
LEFT JOIN orders o
ON o.user_id = u.id
</select>
Spring整合mybatis
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd "><context:property-placeholder location="classpath:jdbc.properties"/><bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="${jdbc.driverClass}"></property><property name="url" value="${jdbc.jdbcUrl}"></property><property name="username" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property></bean><bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><!-- 核心配置文件位置 --><property name="configLocation" value="classpath:SqlMapConfig.xml"></property></bean><!-- <bean name="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"><property name="sqlSessionFactory" ref="sqlSessionFactory"></property><property name="mapperInterface" value="com.zzh.mapper.UserMapper"></property></bean> --> <!-- Mapper动态代理开发 扫描此时spring将自动扫描该配置文件下的sqlSessionFactory,不需手动配置property标签name="basePackgae"指定spring去对应的包中扫描mapper--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.zzh.mapper"></property></bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.jdbcUrl}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 核心配置文件位置 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
</bean>
<!-- <bean name="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="com.zzh.mapper.UserMapper"></property>
</bean> -->
<!-- Mapper动态代理开发 扫描
此时spring将自动扫描该配置文件下的sqlSessionFactory,不需手动配置property标签
name="basePackgae"指定spring去对应的包中扫描mapper
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zzh.mapper"></property>
</bean>
</beans>
<?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.zzh.mapper.UserMapper"><select id="findUserById" parameterType="Integer" resultType="User">select * from `user` where id = #{id}</select>
</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">
<mapper namespace="com.zzh.mapper.UserMapper">
<select id="findUserById" parameterType="Integer" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>
转载于:https://www.cnblogs.com/zzh1997/p/9601130.html
mybatis.zzh相关推荐
- 在vs code中使用yarn报错 - 无法加载文件 C:\Users\zzh\AppData\Roaming\npm\yarn.ps1
yarn : 无法加载文件 C:\Users\zzh\AppData\Roaming\npm\yarn.ps1,因为在此系统上禁止运行脚本.有关详细信 息,请参阅 http://go.microsof ...
- mybatis查询报错:com.mysql.cj.exceptions.DataConversionException: Cannot determine value type from string
mybatis查询报错: com.mysql.cj.exceptions.DataConversionException: Cannot determine value type from strin ...
- MyBatis的插入后获得主键的方式
需求: 使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值. 方法: 在mapper中指定keyProperty属性,示例如下: <insert id=" ...
- mybatis使用注解开发
mybatis使用注解开发 面向接口编程 在之前我们是通过面向对象编程,但是在真正开发的时候我们会选择面向接口编程. 根本原因 : 解耦 , 可拓展 , 提高复用 , 分层开发中 , 上层不用管具体的 ...
- mybatis ResultMap
ResultMap 解决属性名和字段的名称不一致的问题. 查询为null的问题 创建java实体类: public class User {private int id; //idprivate St ...
- mybatis配置文件解析
mybatis配置文件解析 mybatis核心配置文件`mybatis-config.xml文件. mybatis的配置文件包含了会深深影响mybatis行为的设置和属性信息. 能配置的内容: con ...
- mybatis CRUD操作
mybatis CRUD操作 select select标签是mybatis最常用的标签之一. select语句有很多属性可以详细的配置每一天sql语句. id 命名空间唯一的标识. 接口中的方法名与 ...
- java mybatis基础
java mybatis基础 1.1 什么是mybatis? mybatis是一个优秀的持久层框架. 避免几乎所有的JDBC代码和手动设置参数以及获取结果集的过程. 可以使用简单的xml或者注解来配置 ...
- mybatis的资源过滤错误及xml文件编码错误
mybatis 解决maven项目内资源过滤的问题 写的配置文件无法被导出或者生效的问题. 解决方案: <build><resources><resource>&l ...
最新文章
- 算法工程师养成记(附精选面试题)
- 遇见requestAnimationFrame
- LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- boost源码剖析之:Tuple Types(rev#2)
- 初学__Python——Python的流程控制语句 if、for、while
- linux接收手机信号,接收关联设备的信号强度在Linux接入点
- pdo插入mysql数据出错_php中通过pdo插入数据时,sql语句错误?
- javaScript学习笔记之类型转换
- matlab图像分类器,Matlab 基于svm的图像物体分类
- 使用yum快速部署Oracle安装环境 11g
- MPlyaer播放高清视频的说明(CoreAVC、提高速度和清晰度等问题)
- 【转】BAT机器学习面试1000题系列
- WIN10家庭版自动锁屏解决方案
- 基于MATLAB的指纹识别系统【论文,GUI】
- 安装运行太极框架Android搞机操作root
- 四足机器人(从PCB到3D打印)
- Java后端集成发送短信功能(用的是阿里云的短信服务)
- 36岁大数据人被中台问倒,没点架构思维,连面试都过不了?
- 交换机的基础配置学习笔记
- C语言位操作--判断整数的符号