MyBatis

  1. // pojo
  2. User getUserById(int id);
  3. // mapper
  4. <select id="getUserById" parameterType="int" resultType="edu.cqupt.pojo.User">
  5. select * from mybatis.user where id = #{id}
  6. </select>
  7. // test
  8. @Test
  9. public void getUserById(){
  10. SqlSession sqlSession = MybatisUtils.getSqlSession();
  11. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  12. User user = mapper.getUserById(2);
  13. System.out.println(user);
  14. }

resultMap

  1. <!--结果集映射-->
  2. <resultMap id="UserMap" type="User">
  3. <!--column数据库中的字段,property实体类中的属性-->
  4. <result column="id" property="id"/>
  5. <result column="name" property="name"/>
  6. <result column="pwd" property="password"/>
  7. </resultMap>
  8. <select id="getUserById" resultMap="UserMap">
  9. select * from mybatis.user where id = #{id}
  10. </select>

配置

  • configuration(配置)
  • properties(属性)
  • settings(设置)
  • typeAliases(类型别名)
  • typeHandlers(类型处理器)
  • objectFactory(对象工厂)
  • plugins(插件)
  • environments(环境配置)
  • environment(环境变量)
  • transactionManager(事务管理器)
  • dataSource(数据源)
  • databaseIdProvider(数据库厂商标识)
  • mappers(映射器)

日志

• 配置log4j为日志的实现

  1. <settings>
  2. <setting name="logImpl" value="LOG4J"/>
  3. </settings>

配置文件

  • log4j.properties
    1. #将等级为DEBUG的日志信息输出到consolefile这两个目的地,consolefile的定义在下面的代码
    2. log4j.rootLogger=DEBUG,console,file
    3. #控制台输出的相关设置
    4. log4j.appender.console = org.apache.log4j.ConsoleAppender
    5. log4j.appender.console.Target = System.out
    6. log4j.appender.console.Threshold=DEBUG
    7. log4j.appender.console.layout = org.apache.log4j.PatternLayout
    8. log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
    9. #文件输出的相关设置
    10. log4j.appender.file = org.apache.log4j.RollingFileAppender
    11. log4j.appender.file.File=./log/kuang.log
    12. log4j.appender.file.MaxFileSize=10mb
    13. log4j.appender.file.Threshold=DEBUG
    14. log4j.appender.file.layout=org.apache.log4j.PatternLayout
    15. log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
    16. #日志输出级别
    17. log4j.logger.org.mybatis=DEBUG
    18. log4j.logger.java.sql=DEBUG
    19. log4j.logger.java.sql.Statement=DEBUG
    20. log4j.logger.java.sql.ResultSet=DEBUG
    21. log4j.logger.java.sql.PreparedStatement=DEBUG

    分页

    使用Limit分页

    RowBounds 分页

    PageHelper 插件

使用注解开发

  1. public interface UserMapper {
  2. @Select("select * from user")
  3. List<User> getUsers();
  4. // 方法存在多个参数,所有的参数前面必须加上 @Param("id")注解
  5. @Select("select * from user where id = #{id}")
  6. User getUserByID(@Param("id") int id);
  7. @Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
  8. int addUser(User user);
  9. @Update("update user set name=#{name},pwd=#{password} where id = #{id}")
  10. int updateUser(User user);
  11. @Delete("delete from user where id = #{uid}")
  12. int deleteUser(@Param("uid") int id);
  13. }

Lombok

  1. @Getter and @Setter
  2. @FieldNameConstants
  3. @ToString
  4. @EqualsAndHashCode
  5. @AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
  6. @Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger
  7. @Data
  8. @Builder
  9. @Singular
  10. @Delegate
  11. @Value
  12. @Accessors
  13. @Wither
  14. @SneakyThrows

复杂查询

一对多查询

  1. // 按查询嵌套处理
  2. <select id="getTeacher2" resultMap="TeacherStudent2">
  3. select * from mybatis.teacher where id = #{tid}
  4. </select>
  5. <resultMap id="TeacherStudent2" type="Teacher">
  6. <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
  7. </resultMap>
  8. <select id="getStudentByTeacherId" resultType="Student">
  9. select * from mybatis.student where tid = #{tid}
  10. </select>
  1. <!--按结果嵌套查询-->
  2. <select id="getTeacher" resultMap="TeacherStudent">
  3. select s.id sid, s.name sname, t.name tname,t.id tid
  4. from student s,teacher t
  5. where s.tid = t.id and t.id = #{tid}
  6. </select>
  7. <resultMap id="TeacherStudent" type="Teacher">
  8. <result property="id" column="tid"/>
  9. <result property="name" column="tname"/>
  10. <!--复杂的属性,我们需要单独处理 对象: association 集合: collection
  11. javaType="" 指定属性的类型!
  12. 集合中的泛型信息,我们使用ofType获取
  13. -->
  14. <collection property="students" ofType="Student">
  15. <result property="id" column="sid"/>
  16. <result property="name" column="sname"/>
  17. <result property="tid" column="tid"/>
  18. </collection>
  19. </resultMap>

多对一查询

联表查询

也可以使用子查询

  1. <!--
  2. 思路:
  3. 1. 查询所有的学生信息
  4. 2. 根据查询出来的学生的tid,寻找对应的老师! 子查询
  5. -->
  6. <select id="getStudent" resultMap="StudentTeacher">
  7. select * from student
  8. </select>
  9. <resultMap id="StudentTeacher" type="Student">
  10. <result property="id" column="id"/>
  11. <result property="name" column="name"/>
  12. <!--复杂的属性,我们需要单独处理 对象: association 集合: collection -->
  13. <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
  14. </resultMap>
  15. <select id="getTeacher" resultType="Teacher">
  16. select * from teacher where id = #{id}
  17. </select>

image.png

总结:

  • 关联 - association 多对一
  • 集合 - collection 【一对多】

动态 SQL

  1. if
  2. choose (when, otherwise)
  3. trim (where, set)
  4. foreach

IF

  1. <select id="queryBlogIF" parameterType="map" resultType="blog">
  2. select * from mybatis.blog where 1=1
  3. <if test="title != null">
  4. and title = #{title}
  5. </if>
  6. <if test="author != null">
  7. and author = #{author}
  8. </if>
  9. </select>

choose (when, otherwise)

trim (where, set)

foreach

构建 IN 条件语句

  1. <select id="queryBlogForeach" parameterType="map" resultType="Blog">
  2. select * from blog
  3. <where>
  4. <foreach item="id" collection="ids"
  5. open="and (" separator="or" close=")">
  6. id = #{id}
  7. </foreach>
  8. </where>
  9. </select>
  10. @Test
  11. public void queryBlogForeach(){
  12. SqlSession sqlSession = MybatisUtils.getSqlSession();
  13. BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
  14. Map map = new HashMap();
  15. List<String> ids = new ArrayList<String>();
  16. ids.add("bce7cc1ca483454eb925c1c0e6037d5f");
  17. ids.add("3a0b7bbb3faa4bbaad1dcc151fb29769");
  18. ids.add("c6c0616e8f82403cb336696a6f6729af");
  19. map.put("ids",ids);
  20. mapper. queryBlogForeach(map);
  21. sqlSession.close();
  22. }

SQL片段

  1. <sql id="if-title-author">
  2. <if test="title != null">
  3. title = #{title}
  4. </if>
  5. <if test="author != null">
  6. and author = #{author}
  7. </if>
  8. </sql>
  9. <select id="queryBlogIF" parameterType="map" resultType="blog">
  10. select * from mybatis.blog
  11. <where>
  12. <include refid="if-title-author"></include>
  13. </where>
  14. </select>

Dynamic SQL

干掉mapper.xml!MyBatis新特性动态SQL真香!

Dynamic SQL更倾向于使用Java API来实现SQL操作,传统的方式更倾向于在mapper.xml中手写SQL来实现SQL操作。