Mybatis基础

Maven资源导出的配置

!--   build中配置resources,防止资源导出失败-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    
<!--   设置 property 变量 的编码为UTF-8 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

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>
    <!--引入配置文件  可以在其中添加一些配置 如果添加的属性配置与配置文件中属性配置同名 优先使用配置文件中的配置-->
    <properties resource="db.properties"></properties>
<!--    类型别名的配置-->
    <typeAliases>
<!--        给具体的类起一个别名-->
<!--        <typeAlias type="com.demo4.pojo.User" alias="User"></typeAlias>-->
<!--        也可以指定一个包名 MyBatis会在包中搜索需要的javaBan  包中所有的类的别名为类的首字母小写
            若有注解 则别名为其注解的值  
            @Alias("Hello")
            public class User {
            }  -->
        <package name="com.demo4.pojo"></package>
    </typeAliases>
   
<!--环境的配置-->
    <environments default="test">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>

        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

<!--  映射器的配置-->
    <mappers>
<!--        资源绑定 (推荐使用)-->
        <mapper resource="com/demo4/dao/UserMapper.xml"></mapper>
<!--        类绑定  接口和她的mapper配置文件必须同名 接口和她的mapper配置文件必须在同一个包下-->
<!--        <mapper class="com.demo4.dao.UserMapper"></mapper>-->
<!--      扫描包绑定  接口和她的mapper配置文件必须同名 接口和她的mapper配置文件必须在同一个包下   -->
<!--        <package name="com.demo4.dao"></package>-->
    </mappers>

</configuration>

MybatisUtils工具类


public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static  {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

映射的配置

<?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.mybatis.dao.UserMapper">
    <select id="getUserList" resultType="com.mybatis.pojo.User">
        select * from user
      </select>

    <select id="getUser" parameterType="int" resultType="com.mybatis.pojo.User">
    select * from user where id = #{id}
  </select>
<!--    添加-->
    <insert id="insertUser" parameterType="com.mybatis.pojo.User">
        insert into user(id,name,pwd) values(#{id},#{name},#{pwd})
    </insert>
<!--修改-->
    <update id="updateUser" parameterType="com.mybatis.pojo.User">
        update user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>
<!--    删除-->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id = #{id}
    </delete>
</mapper>


//注意点 增删改需要提交事务

数据库中的字段与实体类属性不一致的解决办法

1、在sql语句中对字段与属性不一样的字段起别名
//实体类
public class User {
   private int id;
   private String name;
   private String password;
}
//数据库中的字段 id name pwd
//配置的sql语句
 <select id="getUser" resultType="user" parameterType="_int">
        select id,name,pwd as password from user where id = #{id}
    </select>
2、resultMap
   <resultMap id="userMap" type="user">
<!-- column代表数据库中的字段 property代表实体类中的属性-->
      <result column="id" property="id"></result>
        <result column="name" property="name"></result>
        <result column="pwd" property="password"></result>
    </resultMap>
    <select id="getUser" parameterType="_int"  resultMap="userMap">
        select * from user where id = #{id}
    </select>

Log4j的使用

1、引入依赖
<dependency>
      <groupId>log4j</groupId>
     <artifactId>log4j</artifactId>
     <version>1.2.17</version>
</dependency>
2、创建配置文件log4j.properties 进行配置
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/zhang.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
3、在mybatis-config.xml文件中进行设置
<!--    设置-->
    <settings>
<!--        配置标准的日志工厂-->
<!--        <setting name="logImpl" value="STDOUT_LOGGING"></setting>-->
<!--        配置log4j日志工厂-->
        <setting name="logImpl" value="LOG4J"></setting>
    </settings>

4、在需要使用log4j的类中到包  import org.apache.log4j.Logger;
  参数为  当前类.class
 private static Logger logger = Logger.getLogger(参数);

5、日志级别
logger.info("info: Log4jTest");
logger.debug("info: Log4jTest");
logger.error("info: Log4jTest");

使用注解(适合简单的sql语句)

1、
public interface UserMapper {
    @Select("select * from user")
    List<User> getUserList();
    
   //方法存在多个参数时 要加@Param("id")的注解
   //关于@Param()注解 
   //基本类型和String类型的参数要加
   //引用类型不需添加
   //如果只有一个基本类型的可以忽略 但建议加上

    @Select("select * from user where id = #{id}")
    User getUser(@Param("id") int id);

    @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
    int insertUser(User user);

    @Update("update user set name=#{name},pwd=#{password} where id = #{id}")
    int updateUser(User user);

    @Delete("delete from user where id = #{id}")
    int deleteUser(int id);
}
2、在mybatis-config.xml中绑定接口

  <mappers>
      <mapper class="com.demo5.dao.UserMapper"></mapper>
  </mappers>

mybatis的执行流程

在这里插入图片描述

设置自动提交事务

    // sqlSessionFactory.openSession(true); 参数设置为true会自动提交事务
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }

多表查询(多对一)

例如
多个学生对应一个老师
public class Student {
    private int id;
    private String name;
    private int tid;
    private Teacher teacher;
}
public class Teacher {
    private int id;
    private Striing name
}

sql语句
  <select id="getStudentList2" 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="Student">
        <result property="id" column="sid"></result>
        <result property="name" column="sname"></result>
        //javaType 是属性的类型 oftype为属性的泛型的类型
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"></result>
        </association>
    </resultMap>
  
或

    <select id="getStudentList" resultMap="StudentTeacher">
      select * from student
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"></result>
        <result property="name" column="name"></result>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>
    </resultMap>

    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>

多表查询(一对多)

public class Student {
    private int id;
    private String name;
    private int tid;
}

public class Teacher {
   private int id;
   private String name;
   private List<Student> students;
}

sql查询

 <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid,s.name sname,t.id tid,t.name tname
        from student s,teacher t
        where s.tid = t.id and t.id = #{id}
     </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"></result>
        <result property="name" column="tname"></result>
        <collection property="list" ofType="Student">
            <result property="id" column="sid"></result>
            <result property="name" column="sname"></result>
            <result property="tid" column="tid"></result>
        </collection>
    </resultMap>

或

   <select id="getTeacher" resultMap="TeacherStudent2">
        select * from teacher where id = #{id}
    </select>

    <resultMap id="TeacherStudent2" type="Teacher">
        <collection property="list" javaType="ArrayList" ofType="Student"  select="getStudent" column="id"></collection>
    </resultMap>

    <select id="getStudent" resultType="Student">
        select * from student where tid = #{tid}
    </select>

动态Sql(利用相应的标签来拼接不同条件下的sql语句)

public interface BlogMapper {

    int insertBlog(Blog blog);

    List<Blog> getBlogList(Map<String,Object> map);

    int updateBlog(Map<String,Object> map);

    List<Blog> getBlogForEach(Map<String,Object> map);
}

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.demo8.dao.BlogMapper">
    <insert id="insertBlog" parameterType="Blog">
        insert into blog(id,title,author,create_time,views) values(#{id},#{title},#{author},#{createTime},#{views})
    </insert>

    <select id="getBlogList" parameterType="map" resultType="Blog">
        select * from blog
        <where>
<!--            <if test="title != null" >-->
<!--                title = #{title}-->
<!--            </if>-->
<!--            <if test="author != null">-->
<!--                and author = #{author}-->
<!--            </if>-->
            <choose>
                <when test="title != null">
                    title = #{title}
                </when>
                <when test="author != null">
                    and author = #{author}
                </when>
                <otherwise>
                    and views = #{views}
                </otherwise>
            </choose>
        </where>
    </select>

<!--     sql标签抽取公共的sql语句 提高复用性-->
    <sql id="if-title-author">
        <if test="title != null">
            title = #{title},
        </if>
        <if test="author != null">
            author = #{author}
        </if>
    </sql>

    <update id="updateBlog" parameterType="map">
        update blog
        <set>
            <!-- 引用抽取的公共sql语句-->
            <include refid="if-title-author"></include>
        </set>
        where id = #{id}
    </update>


    <select id="getBlogForEach" parameterType="map" resultType="Blog">
        select * from blog
        where id in
        <foreach collection="ids" item="id" open=" (" close=")" separator=",">
            #{id}
        </foreach>

    </select>
</mapper>

测试foreach的的代码
 @Test
    public void test3() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Map<String,Object> map = new HashMap<String, Object>();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        ids.add(4);
        map.put("ids",ids);
        List<Blog> blogForEach = mapper.getBlogForEach(map);
        for (Blog blog : blogForEach) {
            System.out.println(blog);
        }
        sqlSession.close();
    }

开启全局缓存


 1、在mybatis-config.xml配置文件中设置开启全局缓存
 <settings>
        <setting name="logImpl" value="LOG4j"></setting>
        <!--开启驼峰命名自动转换-->
        <setting name="mapUnderscoreToCamelCase" value="true"></setting>
<!--        开启全局缓存-->
        <setting name="cacheEnabled" value="true"></setting>
    </settings>
2、//默认情况下,只启用了本地的会话缓存(一级),它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行
  <cache eviction="FIFO"
            flushInterval="60000"
            size="512"
            readOnly="true"/>
3、<select useCache="true"></seclect>
注意:
>只要开启二级缓存,在用一个映射文件下有效
>所有的数据会先放在一级缓存中
>只有当会话提交,或关闭时才会提交到耳机缓存中


原文地址:https://blog.csdn.net/weixin_44996454/article/details/122143880

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1.pom.xml引入依赖 &lt;dependency&gt; &lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt; &lt;artifactId&gt;pagehelper&lt;/artifactId&gt; &lt;version&gt;5
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;!DOCTYPE configuration PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot; &qu
准备工作 ① 创建数据库&amp;数据表 ## 创建数据库 CREATE DATABASE `dbtest1`; ## 创建数据表 CREATE TABLE `t_user` ( `id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(20) DEF
MyBatis逆向工程是指根据数据库表结构自动生成对应的实体类、Mapper接口以及SQL映射文件的过程。这个过程可以通过MyBatis提供的逆向工程工具来完成,极大地方便了开发人员,避免了重复的代码编写,提高了开发效率。 创建逆向工程的步骤 1、添加依赖&amp;插件 &lt;!-- 控制Mave
MyBatis获取参数值的两种方式:${}和#{} ${}的本质就是字符串拼接,#{}的本质就是占位符赋值。 ${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自
resultMap作用是处理数据表中字段与java实体类中属性的映射关系。 准备工作 ① 创建数据库&amp;数据表 CREATE DATABASE `dbtest1`; CREATE TABLE `t_emp` ( `emp_id` int NOT NULL AUTO_INCREMENT, `em
EHCache缓存针对于MyBatis的二级缓存。 MyBatis默认二级缓存是SqlSessionFactory级别的。 添加依赖 &lt;!-- MyBatis-EHCache整合包 --&gt; &lt;dependency&gt; &lt;groupId&gt;org.mybatis.cac
MyBatis 提供了一级缓存和二级缓存的支持,用于提高数据库查询的性能,减少不必要的数据库访问。 一级缓存(SqlSession 级别的缓存) 一级缓存是 MyBatis 中最细粒度的缓存,也称为本地缓存。它存在于每个 SqlSession 的生命周期中,当 SqlSession 被关闭或清空时,
动态SQL是 MyBatis 中非常强大且灵活的功能,允许你根据不同的条件构建SQL查询。 这主要通过 &lt;if&gt;、&lt;choose&gt;、&lt;when&gt;、&lt;otherwise&gt;、&lt;foreach&gt;等标签实现。 查询场景 /** * 根据条件查询员工
本教程操作系统:windows10系统、DELL G3电脑。 MyBatis 是一个优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。在 MyBatis 中,配置数据库连接是非常重要的第一步。下面将详细介绍如何配置 MyBatis 的
今天小编给大家分享的是MyBatis批量查询、插入、更新、删除如何实现,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。
今天小编给大家分享的是Mybatis操作多数据源实现的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
本篇文章和大家了解一下mybatis集成到spring的方式有哪些。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。1 前言1.1 集成spring前使用mybat...
今天小编给大家分享的是mybatis-plus分页查询的3种方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
本篇内容主要讲解“mybatis之BaseTypeHandler怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“mybatis...
这篇文章主要介绍了mybatisforeach怎么传两个参数的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇mybatisforeach怎...
这篇“MyBatis映射文件中parameterType与resultType怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的...
这篇文章主要介绍“MyBatis怎么获取自动生成的键值”,在日常操作中,相信很多人在MyBatis怎么获取自动生成的键值问题上存在疑惑,小编查阅了各式资料,整理出
这篇文章主要讲解了“怎么去掉IntelliJIDEA中mybatis对应的xml文件警告”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入...
这篇文章主要介绍“MybatisPlus使用@TableId主键id自增长无效如何解决”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这...