idea使用maven搭建mybatis

首先新建一个maven项目

在这里插入图片描述
如果新建好之后src下的java和resources结构不是这样在这里插入图片描述
右键 Make directorty as 设置即可

在父工程配置jar包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
<!--父工程-->
    <groupId>com.kuang</groupId>
    <artifactId>MyBatis-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis-01</module>
    </modules>
    <!--导入依赖-->
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit、-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>
     <!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
</project>

新建数据库并进行连接

第一次可能会出现时区错误 解决方法如下解决时区错误
在右边的状态栏中选择database后输入账号密码 然后测试连接后即可

Mybatis核心配置文件

在resource下新建一个xml文件 命名一般为 mybatis-config.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核心配置文件-->
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
<!--每一个mapper.XML都需要在mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="com/kuang/dao/userMapper.xml"/>
    </mappers>
</configuration>

如果有很多Mapper 可以这样写
Mapper 接口要同名且在同一个包下

编写工具类

在这里插入图片描述

//sqlSessionFactory
public class MyBatisUtls {
    private  static SqlSessionFactory sqlSessionFactory;
  static {

      try {
          //mybatis第一步获取sqlSeesionFactory对象
          String resource = "mybatis-config.xml";
          InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  //既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。SqlSession 完全包含了面向数据库执行 SQL
    // 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。例如:
public static SqlSession getSqlSession(){
    SqlSession sqlSession = sqlSessionFactory.openSession();
    return  sqlSession;
}
}

编写实体类 实体类要和数据库的对应

编写mapper接口(dao)

写UserMapper.xml文件

将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">
<!--命名空间 绑定一个对应的dao/maopper接口-->
<mapper namespace="com.kuang.dao.UserDao">
  <select id="getUserlist" resultType="com.kuang.pojo.User">
      select * from mybatis.user;
  </select>
</mapper>

测试结果

package com.kuang.dao;

import com.kuang.pojo.User;
import com.kuang.util.MyBatisUtls;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

/**
 * @author w
 */
public class UserDaoTest {
    @Test
    public void test(){
        //第一步 获得sqlSession对象
        SqlSession sqlSession = MyBatisUtls.getSqlSession();
        try{

            //方式1 getMapper
            UserDao mapper = sqlSession.getMapper(UserDao.class);
            List<User> userlist = mapper.getUserlist();
            for (User user:userlist
            ) {
                System.out.println(user);

            }
        }catch (Exception e){
e.printStackTrace();
        }finally {

            sqlSession.close();
        }

    }
}

增删改要记得提交

<!--对象中的属性可以直接取出来使用-->
    <insert id="addUser" parameterType="com.kuang.pojo.User">
        insert into mybatis.user(id, name, pwd) values (#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="com.kuang.pojo.User" >
     update mybatis.user set  name=#{name},pwd=#{pwd}  where id=#{id};
    </update>
    <delete id="deleteUser" parameterType="int" >
        delete from mybatis.user where id=#{id};
    </delete>
   @Test
    public void deleteUser(){
        SqlSession sqlSession = MyBatisUtls.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(3);
        sqlSession.commit();
        sqlSession.close();
    }

如果出现实体类参数过多的情况建议使用map

UserMapper.xml

<insert id="addUser2" parameterType="map">
        insert into mybatis.user(id, name, pwd) values (#{userid},#{userName},#{passWord});
    </insert>

测试方法中

 @Test
    public void addUser2(){
        SqlSession sqlSession = MyBatisUtls.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userid",6);
        map.put("userName","wxxx");
        map.put("passWord","222");
        mapper.addUser2(map);
        sqlSession.commit();
        sqlSession.close();
    }

使用resultMap解决类名和数据库字段不一致的问题

类似重命名

<resultMap id="UserMap" type="com.kuang.pojo.User">
    <!--column数据库的字段 property实体类中的属性-->
<!--    <result column="id" property="id"></result>
    <result column="name" property="name"></result>-->
    <result column="pwd" property="password"></result>
</resultMap>
    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select * from mybatis.user where id=#{id}
    </select>

日志

数据库操作出现异常打印错误信息
mybatis自带日志输出
掌握log4j和stdout_logging

stdout_logging

stdout_logging标准日志输出
配置日志 在mybatis-config,xml中

  <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

LOG4J

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

log4j.properties的配置

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/w.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

配置log4j为日志的实现

 <setting name="logImpl" value="LOG4J"/>
    

简单使用log4j

使用中如果导包是import org.apache.log4j.Logger;
日志对象,参数为当前类的class

 static Logger logger = Logger.getLogger(UserMapperTest.class);

日志级别

 logger.info("info:进入testLLog4j");
            logger.debug("debug run");
            logger.error("error run");

分页

select *  from table  limit pageIndex,pageSize

接口
//分页
List getUserByLimit(Map<String,Integer> map);

xml

  <!--getUserByLimit 分页-->
    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select  * from mybatis.user limit #{startIndex},#{pageSize}
    </select>

测试方法

 SqlSession sqlSession = MyBatisUtls.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",1);
    map.put("pageSize",3);
    List<User> userList = mapper.getUserByLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }```



注解 sql

注解直接在接口上实现
本质是反射



@Select("select * from user")
List<User> getUser();

在配置文件中绑定接口 这个是必须的
 <!--绑定接口-->
    <mappers>
        <mapper class="com.kuang.dao.UserMapper"></mapper>
    </mappers>```
实现


 public void test(){
    SqlSession sqlSession = MyBatisUtls.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> user = mapper.getUser();
    for (User user1 : user) {
        System.out.println(user1);
    }
    sqlSession.close();
}```

# 关于@Param()注解
基本类型的参数或者String类型需要加上
引用类型不用
如果只有一个基本类型 可以忽略 但是建议加
我们在Sql中引用的就是我们这里的@Param()中设定的属性名

# 多对一处理
mybatis-config.xml中配置mapper.xml也可以这样

``` 方法1按照查询嵌套处理 查询所有学生信息 根据查询出来的tid寻找对应的老师 ``` select * from student
</resultMap>
select * from teacher where id=#{id} ```

方法2按照结果嵌套处理
此法稍微简单一点

  <!--按照结果嵌套处理-->
    <select id="getStudent2" resultMap="StudentTeacher2">
        select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
    </select>
    <resultMap id="StudentTeacher2" type="com.kuang.pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="com.kuang.pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

一对多处理

一个老师对应多个学生
老师实体类

  private int id;
    private String name;
//一个老师多个学生
    private List<Student> students;

学生的实体类

  private  int id;
    private  String name;
private int tid;``

xml的写法
如果是List 泛型的话要在collection中用ofType 不能使用javaType

    <!--按结果嵌套-->
<select id="getTeacher" resultMap="TeacherStudent">
  select s.id sid, s.name sname,t.name tname , t.id tid from student s,teacher t where s.tid=t.id and t.id=#{tid}
</select>
    <resultMap id="TeacherStudent" type="com.kuang.pojo.Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="com.kuang.pojo.Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
        </collection>
            </resultMap>

测试代码


 public void  test1(){
        SqlSession sqlSession = MyBatisUtls.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
      //  List<Teacher> teacherList = mapper.getTeacher();
        Teacher teacher1 = mapper.getTeacher(1);
        System.out.println(teacher1);
        /*for (Teacher teacher : teacherList) {
            System.out.println(teacher);
        }*/
        sqlSession.close();
    }

在这里插入图片描述

动态sql

开启驼峰命名在mybais-config.xml中

 <setting name="mapUnderscoreToCamelCase" value="true"/>

if语句 在xml中

<select id="queryBlogIF" parameterType="map" resultType="com.kuang.pojo.Blog">
    select * from blog where 1=1
    <if test="title != null">
and title =#{title}
    </if>
    <if test="author != null">
        and author =#{author}
    </if>
</select>

choose (when ,otherwise)类似switch语句
条件顺序判断,满足一个 后面就不拼接
如果第一个不满足 第二个满足 系统会自动去除到第二个的and

 <select id="queryBlogChoose" parameterType="map" resultType="com.kuang.pojo.Blog">
         select * from blog
         <where>
             <choose>
                 <when test="title != null">
                     title =#{title}
                 </when>
                 <when test="author != null">
                     and author =#{author}
                 </when>
                 <otherwise>
                     and views = #{views}
                 </otherwise>
             </choose>

         </where>
    </select>

trim(where set)
where 解决代码拼接的问题

   <where>
        <if test="title != null">
            and title =#{title}
        </if>
        <if test="author != null">
            and author =#{author}
        </if>

    </where>

set语句

<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <if test="title != null">
            title =#{title},
        </if>
        <if test="author != null" >
            author =#{author}
        </if>
    </set>
    where id =#{id}
</update>

动态sql的本质还是sql语句 只是可以在sql层面执行一些逻辑代码

SQL片段

将重复的代码提取出来 复用

 <sql id="if-title-author">
        <if test="title != null">
            title =#{title},
        </if>
        <if test="author != null" >
            author =#{author}
        </if>
    </sql>

然后在需要的地方使用include标签引用

<update id="updateBlog" parameterType="map">
    update blog
    <set>
       <include refid="if-title-author"></include>
    </set>
    where id =#{id}
</update>

注意 最好基于单表定义sql片段
不要存在where标签
尽量只要if即可

foreach

一般是在对集合进行遍历 通常是在in 条件语句的时候
xml中的代码

   <select id="queryBlogForeach" parameterType="map" resultType="com.kuang.pojo.Blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
    id=#{id}
</foreach>
</where>
    </select>

测试类中

SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        map.put("ids",ids);
        List<Blog> blogList = mapper.queryBlogForeach(map);
        for (Blog blog : blogList) {
            System.out.println(blog);
        }
        sqlSession.close();```
    

动态sql就是在拼接sql语句 只要保证sql的准确性 按照sql的格式排列组合即可

# 缓存
将查询结果,暂存到一个可以直接取到的地方,下次可以节约资源

经常查询并且不经常改变【可以使用缓存】
测试缓存要开启日志
映射文件中的select 的结果会被缓存 
insert delete update 会刷新缓存
一级缓存默认开启只在一次sqlSession中有效

使用二级缓存
开启全局缓存 在mybatis-config中配置

``` 配置好后 如果需要使用二级缓存 只需要在sql映射文件(mapper.xml)中添加一个标签 如果只用cache 这个标签可能会报序列化的错误 所有数据都会存在一级缓存 只有当会话提交或者关闭的时候才会提交到二级缓存中 二级缓存在同一个mapper下有效
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值