ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Mybatis基础

2022-01-02 11:39:50  阅读:105  来源: 互联网

标签:name 基础 private log4j Mybatis where id select


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>
注意:
>只要开启二级缓存,在用一个映射文件下有效
>所有的数据会先放在一级缓存中
>只有当会话提交,或关闭时才会提交到耳机缓存中


标签:name,基础,private,log4j,Mybatis,where,id,select
来源: https://blog.csdn.net/weixin_44996454/article/details/122143880

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有