下载jar包
mybaits的代码由github.com下载地址:link
部署jar包
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
编写MyBatis核心配置文件(configuration.xml)
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/MyBatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
dataSource>
environment>
environments>
configuration>
创建实体类
public class UserPojo {
private Integer id; //id
private String userCode; //用户编码
private String userName; //用户名称
private String userPassword; //用户密码
private Integer gender; //性别
private Data birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer userRole; //用户角色id
private Integer createdBy; //创建者
private Data creationDate; //创建时间
private Integer modifyBy; //更新者
private Data modifyDate; //更新时间
}
public interface UserMapper {
/**
* 查询用户列表(参数,对象入参)
* @param userPojo
* @return
*/
public List<UserPojo> getUserList(UserPojo userPojo);
/**
* 查询用户列表(参数:Map)
* @param userMap
* @return
*/
public List<UserPojo> getUserListByMap(Map<String,String> userMap);
创建SQL映射文件
<mapper namespace="user">
<select id="findUserById" parameterType="Integer" resultType="com.ali.pojo.User">
select * from t_user where id=#{v}
select>
mapper>
编写测试类
public class UserMapperTest {
@Test
public void testGetUserList(){
SqlSession sqlSession=null;
List<UserPojo> userPojoList=new ArrayList<>();
try {
sqlSession= MybatisUtil.open();
UserPojo userPojo=new UserPojo();
userPojo.setUserName("赵");
userPojo.setUserRole(3);
userPojoList=sqlSession.getMapper(UserMapper.class).getUserList(userPojo);
} catch (Exception e) {
e.printStackTrace();
} finally {
MybatisUtil.close(sqlSession);
}
for (UserPojo userPojo: userPojoList ) {
System.out.println("testGetUsetList UserCode:"+userPojo.getUserCode()+"and userName:" +userPojo.getUserName());
}
}
}
核心接口和类
SqlSessionFactoryBuilder
(1)、SqlSessionFactoryBuilder负责构建SqlSessionFactory。
(2)、生命周期:用过即丢,,一旦创建了 SqlSessionFactory,就不再需要它了。
(3)、作用域:SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域。
MyBatis核心配置文件(mybatis-config.xml)
SqlMapConfig.xml中配置的内容和顺序如下:
properties(属性)
settings(全局配置参数)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境集合属性对象)
environment(环境子属性对象)
transactionManager(事务管理)
dataSource(数据源)
mappers(映射器)
SQL映射(mapper.xml)
MyBatis 真正强大之处就在于SQL映射语句,也是它的魅力所在,相处于它强大的功能,SQL映射文件的配置确非常简单。
(1)、Mapper:映射文件的根元素节点,只有一个属性namespace(命令空间),其作用如下:
用于区分不同的mapper,全局唯一
(2) 、cache:配置给定命名空间的缓存
(3) 、 cahe-ref: 从其他命名空间引用缓存配置
(4) 、 resultMap: 用来描述数据库结果集和对象的对应关系
(5) 、 sql:可以重用的SQL,也可以被其他语句引用
(6) 、 insert :映射插入语句。
(7) 、 delete:映射删除语句。
(8) 、 select:映射查询语句。
<select id="getUserListByUserName" resultType="User" parameterType="string">
select * from smbms_user where userName like concat('%',#{userName},'%')
select>
<insert id="add" parameterType="User">
insert into smbms_user (userCode,userName,userPassword,gender,birthday,phone,address,userRole,createdBy,creationDate) values (#{userCode},#{userName},#{userPassword},#{gender},#{birthday},#{phone},#{address},#{userRole},#{createdBy},#{creationDate})
insert>
<resultMap type="User" id="userList">
<result property="id" column="id"/>
<result property="userName" column="userName"/>
<result property="userRloeName" column="rloeName"/>
resultMap>
<update id="modify" parameterType="User">
update smbms_user set userCode=#{userCode},userName=#{userName},userPassword=# {userPassword},phone=#{phone} where id = #{id}
update>
<delete id="deleteUserById" parameterType="Integer">
delete from smbms_user where id=#{id}
delete>
association:一对一映射
<association property="permission">
<id column="permissionId" property="id">id>
<result column="pname" property="name">result>
<result column="level" property="level">result>
association>
一对多映射:collection
<collection property="实体类字段名" ofType="list的数据类型">
<id column="permissionId" property="id">id>
<result column="pname" property="name">result>
collection>
什么是动态SQL
动态SQL是MyBatis的一个强大的特性。
使用if查询操作
<select id="getUserList4" resultMap="userList4">
select u.*,r.rloeName
from smbms_user u,smbms_role r
where u.userRole = r.id
<if test="userRole !=null">
and u.userRole = #{userRole}
if>
<if test="userName !=null and userName != ''">
and u.userName like concat('%',#{userName},'%')
if>
select>
使用where实现多条件查询操作
<select id="getUserList5" resultType="pojo.User">
select * from smbms_user
<where>
<if test="userName !=null and userName !=''">
and userName like concat('%',#{userName},'%')
if>
<if test="userRole != null">
and userRole = #{userRole}
if>
where>
select>
使用 trim实现多条件查询操作
<select id="getUserList6" resultType="pojo.User">
select * from smbms_user
<trim prefix="where" prefixOverrides="and | or">
<if test="userName !=null and userName !=''">
and userName like concat('%',#{userName},'%')
if>
<if test="userRole != null">
and userRole = #{userRole}
if>
trim>
select>
使用set更新操作
<update id="modify" parameterType="pojo.User">
update smbms_user
<set>
<if test="userCode !=null">userCode=#{userCode},if>
<if test="userName !=null">userName=#{userName},if>
<if test="userPassword !=null">userPassword=#{userPassword},if>
<if test="gender !=null">userCode=#{gender},if>
<if test="birthday !=null">userCode=#{birthday},if>
<if test="phone !=null">userCode=#{phone},if>
<if test="address !=null">userCode=#{address},if>
<if test="userRole !=null">userCode=#{userRole},if>
<if test="createdBy !=null">userCode=#{createdBy},if>
<if test="modifyDate !=null">userCode=#{modifyDate},if>
set>
where id =#{id}
update>
使用foreach完成复杂查询
<select id="getUserByRoleId_foreach_list" resultMap="userMapByRole1">
select * from smbms_user where userRole in
#{roleList}
foreach>
select>
<resultMap id="userMapByRole1" type="pojo.User">
<id property="id" column="id">id>
<result column="userCode" property="userCode">result>
<result property="userName" column="userName">result>
resultMap>
choose(where、otherwise)
<select id="getUserlist_chose" resultType="pojo.User">
select * from smbms_user where 1=1
<choose>
<when test="userName != null and userName != ''">
and userName like concat('%',#{userName},'%')
when>
<when test="userCode !=null and userCode !=''">
and userCode like concat('%',#{userCode},'%')
when>
<when test="userRole != null">
and userRole=#{userRole}
when>
<otherwise>
and year (creatiomDate) = YEAR (#{creatonDate})
otherwise>
choose>
select>
and userRole=#{userRole}
and year (creatiomDate) = YEAR (#{creatonDate})
```