MyBatis 教程 ——检视阅读

准备

官网文档-中文

教程地址yiibai,质量很差

教程地址w3cschool,纯理论,还不如直接看官网文档

教程地址Mybatis框架入门教程,Oracle

Maven官网

maven pom依赖搜索

回答

  1. 这个教程大体在讲什么?
  2. 教程细部说了什么?
  3. 是否同意教程的知识和观点,同意程度?
  4. 该教程为了带来了什么?

前言

MyBatis 消除 了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。

每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。

  1. xml文件构建SqlSessionFactory实例是非常简单的事情。推荐在这个配置中使用类路径资源(classpath resource),但你可以使用任何Reader实例,包括用文件路径或file://开头的url创建的实例。MyBatis有一个实用类----Resources,它有很多方法,可以方便地从类路径及其它位置加载资源。

MyBatis 最强大的特性之一就是它的动态语句功能。如果您以前有使用JDBC或者类似框架的经历,您就会明白把SQL语句条件连接在一起是多么的痛苦,要确保不能忘记空格或者不要在columns列后面省略一个逗号等。

MyBatis环境配置搭建项目

上来直接构建一个经典的maven web项目。

前提:

  1. #数据库、表
  2. CREATE DATABASE hello_mybatis;
  3. USE hello_mybatis;
  4. CREATE TABLE `t_user` (
  5. `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  6. `name` varchar(64) NOT NULL COMMENT '姓名',
  7. `dept` varchar(254) NOT NULL COMMENT '部门',
  8. `phone` varchar(16) NOT NULL COMMENT '电话',
  9. `height` decimal(10,2) DEFAULT NULL COMMENT '身高',
  10. `create_emp` bigint(20) NOT NULL COMMENT '创建人',
  11. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  12. `modify_emp` bigint(20) DEFAULT NULL COMMENT '修改人',
  13. `modify_time` datetime DEFAULT NULL COMMENT '修改时间',
  14. PRIMARY KEY (`id`),
  15. KEY `idx_name` (`name`)
  16. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='用户表';
  17. INSERT INTO `hello_mybatis`.`t_user` (`name`, `dept`, `phone`, `height`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  18. ( '大青山', 'amy empire', '18956563229', '1.85', '1', '2020-03-31 14:17:35', '1', '2020-03-31 14:17:47');
  19. INSERT INTO `hello_mybatis`.`t_user` (`name`, `dept`, `phone`, `height`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  20. ( '池寒枫', 'amy empire', '22056545', '1.83', '1', '2020-03-31 14:17:35', '1', '2020-03-31 14:17:47');

代码示例:

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <typeAliases>
  6. <typeAlias alias="User" type="com.self.bean.User" />
  7. </typeAliases>
  8. <environments default="development">
  9. <environment id="development">
  10. <transactionManager type="JDBC" />
  11. <dataSource type="POOLED">
  12. <property name="driver" value="com.mysql.jdbc.Driver" />
  13. <property name="url" value="jdbc:mysql://127.0.0.1:3306/hello_mybatis" />
  14. <property name="username" value="root" />
  15. <property name="password" value="123456" />
  16. </dataSource>
  17. </environment>
  18. </environments>
  19. <mappers>
  20. <mapper resource="com/self/dao/UserMapper.xml" />
  21. </mappers>
  22. </configuration>

注意: 对应的是UserMapper.xml在classpath下的地址,后缀.xml要带上(下面的报错就是文件名没有后缀),路径地址要对,否则会报错。

  1. Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/self/dao/UserMapper

UserMapper.xml

CRUD 的sql在各个对应的Mapper 映射文件上写。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.self.dao.UserMapper">
  5. <select id="getUserById" parameterType="int" resultType="User">
  6. select * from `t_user` where id = #{id}
  7. </select>
  8. </mapper>

bean,数据库的映射对象实体类。

  1. public class User {
  2. /**
  3. * id
  4. */
  5. private int id;
  6. /**
  7. * 名字
  8. */
  9. private String name;
  10. /**
  11. * 部门,帝国
  12. */
  13. private String dept;
  14. /**
  15. * 联系号码
  16. */
  17. private String phone;
  18. /**
  19. * 身高
  20. */
  21. private BigDecimal height;
  22. /**
  23. * 创建人
  24. */
  25. private Long createEmp;
  26. /**
  27. * 创建时间
  28. */
  29. private String createTime;
  30. /**
  31. * 修改人
  32. */
  33. private Long modifyEmp;
  34. /**
  35. * 修改时间
  36. */
  37. private String modifyTime;
  38. public int getId() {
  39. return id;
  40. }
  41. public void setId(int id) {
  42. this.id = id;
  43. }
  44. //其他省略
  45. }

main方法。

  1. public class HelloTest {
  2. private static SqlSessionFactory sqlSessionFactory;
  3. private static Reader reader;
  4. static {
  5. try {
  6. reader = Resources.getResourceAsReader("mybatis-config.xml");
  7. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. public static SqlSessionFactory getSessionFactory(){
  13. return sqlSessionFactory;
  14. }
  15. public static void main(String[] args) {
  16. SqlSession sqlSession = getSessionFactory().openSession();
  17. try {
  18. //我们通过调用UserMapper.xml的namespace + id(方法名)来完成数据库访问
  19. User user = (User)sqlSession.selectOne("com.self.dao.UserMapper.getUserById", 1);
  20. System.out.println(JSON.toJSONString(user));
  21. } finally {
  22. sqlSession.close();
  23. }
  24. }
  25. }

输出:

  1. {"dept":"amy empire","height":1.75,"id":1,"name":"艾米","phone":"18956563228"}

配置解释:

  1. 配置文件 mybatis-config.xml 是 mybatis 用来建立 sessionFactory,里面主要包含了数据库连接相关内容,还有 java 类所对应的别名,比如: 这个别名非常重要,在具体的类的映射中,比如:UserMapper.xml 中 resultType 就是对应这个。
  2. mybatis-config.xml 里面 的是包含要映射的类(UserMapper.java)的 xml 配置文件。
  3. 在UserMapper.xml 文件里面主要是定义各种 SQL 语句,以及这些语句的参数,以及要返回的类型等等。

Mybatis接口注解 (项目中一般不使用)

示例:

创建DAO接口

  1. package com.self.dao;
  2. import com.self.bean.User;
  3. import org.apache.ibatis.annotations.Select;
  4. public interface UserMapper {
  5. @Select("SELECT * FROM t_user where name =#{name}")
  6. public User getUserByName(String name);
  7. }

mybatis-config.xml 配置文件不需要配置mappers,转而在sqlSessionFactory.getConfiguration().addMapper(IUser.class);里添加。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <typeAliases>
  6. <typeAlias alias="User" type="com.self.bean.User" />
  7. </typeAliases>
  8. <environments default="development">
  9. <environment id="development">
  10. <transactionManager type="JDBC" />
  11. <dataSource type="POOLED">
  12. <property name="driver" value="com.mysql.jdbc.Driver" />
  13. <property name="url" value="jdbc:mysql://127.0.0.1:3306/hello_mybatis" />
  14. <property name="username" value="root" />
  15. <property name="password" value="123456" />
  16. </dataSource>
  17. </environment>
  18. </environments>
  19. <!--<mappers>-->
  20. <!--<mapper resource="com/self/dao/UserMapper.xml" />-->
  21. <!--</mappers>-->
  22. </configuration>

User 实体类不变。

测试类

  1. public class HelloTest {
  2. private static SqlSessionFactory sqlSessionFactory;
  3. private static Reader reader;
  4. static {
  5. try {
  6. reader = Resources.getResourceAsReader("mybatis-config.xml");
  7. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  8. //在sqlSessionFactory中添加Mapper
  9. sqlSessionFactory.getConfiguration().addMapper(UserMapper.class);
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. public static SqlSessionFactory getSessionFactory(){
  15. return sqlSessionFactory;
  16. }
  17. public static void main(String[] args) {
  18. SqlSession sqlSession = getSessionFactory().openSession();
  19. try {
  20. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  21. User user = userMapper.getUserByName("大青山");
  22. System.out.println(JSON.toJSONString(user));
  23. } finally {
  24. sqlSession.close();
  25. }
  26. }
  27. }

Mybatis增删改查(CURD)

示例:

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <typeAliases>
  6. <typeAlias alias="User" type="com.self.bean.User" />
  7. </typeAliases>
  8. <environments default="development">
  9. <environment id="development">
  10. <transactionManager type="JDBC" />
  11. <dataSource type="POOLED">
  12. <property name="driver" value="com.mysql.jdbc.Driver" />
  13. <property name="url" value="jdbc:mysql://127.0.0.1:3306/hello_mybatis" />
  14. <property name="username" value="root" />
  15. <property name="password" value="123456" />
  16. </dataSource>
  17. </environment>
  18. </environments>
  19. <mappers>
  20. <mapper resource="com/self/dao/UserMapper.xml" />
  21. </mappers>
  22. </configuration>

User 实体类不变。

dao层接口

  1. public interface UserMapper {
  2. public User getUserById(Integer id);
  3. public List<User> getUsers();
  4. public void insert(User user);
  5. public void update(User user);
  6. public void deleteById(Integer id);
  7. }

Mapper 映射文件 : src\main\resources\com\self\dao\UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.self.dao.UserMapper">
  5. <select id="getUserById" parameterType="int" resultType="User">
  6. select * from `t_user` where id = #{id}
  7. </select>
  8. <select id="getUsers" resultType="User">
  9. select * from `t_user` where 1 = 1
  10. </select>
  11. <insert id="insert" parameterType="User">
  12. insert into t_user(`name`, `dept`, `phone`, `height`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  13. (#{name},#{dept},#{phone},#{height},#{createEmp},#{createTime},#{modifyEmp},#{modifyTime})
  14. </insert>
  15. <delete id="deleteById" parameterType="Integer">
  16. delete from t_user where id = #{id}
  17. </delete>
  18. <update id="update" parameterType="User">
  19. update t_user
  20. <set>
  21. <if test="name != null">
  22. name = #{name},
  23. </if>
  24. <if test="dept != null">
  25. dept = #{dept},
  26. </if>
  27. <if test="phone != null">
  28. phone = #{phone},
  29. </if>
  30. <if test="height != null">
  31. height = #{height},
  32. </if>
  33. <if test="modifyEmp != null">
  34. modify_emp = #{modifyEmp},
  35. </if>
  36. <if test="modifyTime != null">
  37. modify_time = #{modifyTime}
  38. </if>
  39. </set>
  40. where id = #{id}
  41. </update>
  42. </mapper>

测试类

  1. package com.self;
  2. import com.alibaba.fastjson.JSON;
  3. import com.self.bean.User;
  4. import com.self.dao.UserMapper;
  5. import org.apache.ibatis.io.Resources;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactory;
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  9. import java.io.IOException;
  10. import java.io.Reader;
  11. import java.math.BigDecimal;
  12. import java.util.Date;
  13. import java.util.List;
  14. public class HelloTest {
  15. private static SqlSessionFactory sqlSessionFactory;
  16. private static Reader reader;
  17. static {
  18. try {
  19. reader = Resources.getResourceAsReader("mybatis-config.xml");
  20. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  21. //在sqlSessionFactory中添加Mapper
  22. //sqlSessionFactory.getConfiguration().addMapper(UserMapper.class);
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. public static SqlSessionFactory getSessionFactory(){
  28. return sqlSessionFactory;
  29. }
  30. public static void main(String[] args) {
  31. SqlSession sqlSession = getSessionFactory().openSession();
  32. try {
  33. //我们通过调用UserMapper.xml的namespace + id(方法名)来完成数据库访问
  34. UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
  35. User user = new User();
  36. user.setCreateEmp(3L);
  37. user.setCreateTime(new Date());
  38. user.setDept("矮人王国");
  39. user.setHeight(new BigDecimal("1.53"));
  40. user.setModifyEmp(3L);
  41. user.setModifyTime(new Date());
  42. user.setPhone("852-253521");
  43. user.setName("霍恩斯");
  44. userMapper.insert(user);
  45. User user1 = new User();
  46. user1.setCreateEmp(3L);
  47. user1.setCreateTime(new Date());
  48. user1.setDept("矮人王国");
  49. user1.setHeight(new BigDecimal("1.53"));
  50. user1.setModifyEmp(3L);
  51. user1.setModifyTime(new Date());
  52. user1.setPhone("852-253521");
  53. user1.setName("霍恩斯-克隆");
  54. userMapper.insert(user1);
  55. sqlSession.commit();
  56. System.out.println("--------------------insert---------------------");
  57. User user2 = userMapper.getUserById(4);
  58. System.out.println("-----getUserById----"+JSON.toJSONString(user2));
  59. User updateUser = new User();
  60. updateUser.setDept("森林矮人王国");
  61. updateUser.setHeight(new BigDecimal("1.56"));
  62. updateUser.setModifyEmp(6L);
  63. updateUser.setModifyTime(new Date());
  64. updateUser.setPhone("852-253521");
  65. updateUser.setName("霍恩斯");
  66. updateUser.setId(user2.getId());
  67. userMapper.update(updateUser);
  68. sqlSession.commit();
  69. System.out.println("--------------------update---------------------");
  70. List<User> users = userMapper.getUsers();
  71. System.out.println("----before delete-----"+JSON.toJSONString(users));
  72. userMapper.deleteById(5);
  73. sqlSession.commit();
  74. System.out.println("--------------------deleteById---------------------");
  75. List<User> afterUsers = userMapper.getUsers();
  76. System.out.println("----before delete-----"+JSON.toJSONString(afterUsers));
  77. } finally {
  78. sqlSession.close();
  79. }
  80. }
  81. }

输出:

  1. --------------------insert---------------------
  2. -----getUserById----{"dept":"矮人王国","height":1.53,"id":4,"name":"霍恩斯","phone":"852-253521"}
  3. --------------------update---------------------
  4. ----before delete-----[{"dept":"amy empire","height":1.75,"id":1,"name":"艾米","phone":"18956563228"},{"dept":"amy empire","height":1.85,"id":2,"name":"大青山","phone":"18956563229"},{"dept":"amy empire","height":1.83,"id":3,"name":"池寒枫","phone":"22056545"},{"dept":"森林矮人王国","height":1.56,"id":4,"name":"霍恩斯","phone":"852-253521"},{"dept":"矮人王国","height":1.53,"id":5,"name":"霍恩斯-克隆","phone":"852-253521"}]
  5. --------------------deleteById---------------------
  6. ----before delete-----[{"dept":"amy empire","height":1.75,"id":1,"name":"艾米","phone":"18956563228"},{"dept":"amy empire","height":1.85,"id":2,"name":"大青山","phone":"18956563229"},{"dept":"amy empire","height":1.83,"id":3,"name":"池寒枫","phone":"22056545"},{"dept":"森林矮人王国","height":1.56,"id":4,"name":"霍恩斯","phone":"852-253521"}]

注意:在增加,更改,删除的时候需要调用 session.commit() 来提交事务,这样才会真正对数据库进行操作提交保存,否则操作没有提交到数据中。

注意:

1、如果在mybatis-config.xml没有配置mapper的xml文件就会报下面的UserMapper is not known to the MapperRegistry.

  1. Exception in thread "main" org.apache.ibatis.binding.BindingException: Type interface com.self.dao.UserMapper is not known to the MapperRegistry.
  2. at org.apache.ibatis.binding.MapperRegistry.getMapper

2、如果插入的数据与字段不匹配个数会报Column count doesn't match value count at row 1。

  1. ### SQL: insert into t_user(`name`, `dept`, `phone`, `height`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES (?,?,?,?,?,?,?,?,?)
  2. ### Cause: java.sql.SQLException: Column count doesn't match value count at row 1

Mybatis表关联一对多

准备:

  1. CREATE TABLE `t_weibo` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3. `user_id` int(10) unsigned NOT NULL COMMENT '用户id',
  4. `title` varchar(254) NOT NULL COMMENT '主题',
  5. `content` text DEFAULT NULL COMMENT '内容',
  6. `create_emp` bigint(20) NOT NULL COMMENT '创建人',
  7. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  8. `modify_emp` bigint(20) DEFAULT NULL COMMENT '修改人',
  9. `modify_time` datetime DEFAULT NULL COMMENT '修改时间',
  10. PRIMARY KEY (`id`),
  11. KEY `idx_user_id` (`user_id`)
  12. ) ENGINE=InnoDB AUTO_INCREMENT= 1000 DEFAULT CHARSET=utf8 COMMENT='微博帖子表';
  13. INSERT INTO `hello_mybatis`.`t_weibo` ( `user_id`, `title`, `content`, `create_emp`, `create_time`, `modify_emp`, `modify_time`)
  14. VALUES ( '4', '霍恩斯描述', '由于矮人种族的原因,他无法成为龙骑士,但这并不影响他在小佣兵团以及整个人神大战中快速成为超级巨星,擅长谋略尤擅兵法让他成为矮人的异类。', '2', '2020-04-01 13:47:24', '2', '2020-04-01 13:47:31');
  15. INSERT INTO `hello_mybatis`.`t_weibo` ( `user_id`, `title`, `content`, `create_emp`, `create_time`, `modify_emp`, `modify_time`)
  16. VALUES ( '4', '霍恩斯与莹', '艾米、大青山、霍恩斯、池傲天、沙若等佣兵团骨干可以逃脱,那些培养了2年多的人才必然全军覆没。', '2', '2020-04-01 13:47:24', '2', '2020-04-01 13:47:31');
  17. INSERT INTO `hello_mybatis`.`t_weibo` ( `user_id`, `title`, `content`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  18. ( '2', '大青山描述', '史料记载中第一个神圣巨龙使骑士,在所有的文明中,他都是传统骑士准则的典范,正直、善良、忠诚、守信、怜悯等一切人类美德的拥有者。人龙神三人组合中的一人。在神界受到龙神以黄金凤的胁迫,毅然解除与冰系神圣巨龙使泰穆格尔赛的龙骑士契约,解除龙神的威胁,后与光明神同归于尽。', '2', '2020-04-01 13:47:24', '2', '2020-04-01 13:47:31');

实例:

  1. public class User {
  2. /**
  3. * id
  4. */
  5. private int id;
  6. /**
  7. * 名字
  8. */
  9. private String name;
  10. /**
  11. * 部门,帝国
  12. */
  13. private String dept;
  14. /**
  15. * 联系号码
  16. */
  17. private String phone;
  18. /**
  19. * 身高
  20. */
  21. private BigDecimal height;
  22. private List<Weibo> weibos;
  23. /**
  24. * 创建人
  25. */
  26. private Long createEmp;
  27. /**
  28. * 创建时间
  29. */
  30. private Date createTime;
  31. /**
  32. * 修改人
  33. */
  34. private Long modifyEmp;
  35. /**
  36. * 修改时间
  37. */
  38. private Date modifyTime;
  39. public List<Weibo> getWeibos() {
  40. return weibos;
  41. }
  42. public void setWeibos(List<Weibo> weibos) {
  43. this.weibos = weibos;
  44. }
  45. //其他省略
  46. }
  47. public class Weibo {
  48. /**
  49. * id
  50. */
  51. private int id;
  52. /**
  53. * 主题
  54. */
  55. private String title;
  56. /**
  57. * 内容
  58. */
  59. private String content;
  60. /**
  61. * 用户信息
  62. */
  63. private User user;
  64. /**
  65. * 创建人
  66. */
  67. private Long createEmp;
  68. /**
  69. * 创建时间
  70. */
  71. private Date createTime;
  72. /**
  73. * 修改人
  74. */
  75. private Long modifyEmp;
  76. /**
  77. * 修改时间
  78. */
  79. private Date modifyTime;
  80. public int getId() {
  81. return id;
  82. }
  83. public void setId(int id) {
  84. this.id = id;
  85. }

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <typeAliases>
  6. <typeAlias alias="User" type="com.self.bean.User" />
  7. <typeAlias type="com.self.bean.Weibo" alias="Weibo"/>
  8. </typeAliases>
  9. <environments default="development">
  10. <environment id="development">
  11. <transactionManager type="JDBC" />
  12. <dataSource type="POOLED">
  13. <property name="driver" value="com.mysql.jdbc.Driver" />
  14. <property name="url" value="jdbc:mysql://127.0.0.1:3306/hello_mybatis" />
  15. <property name="username" value="root" />
  16. <property name="password" value="123456" />
  17. </dataSource>
  18. </environment>
  19. </environments>
  20. <mappers>
  21. <mapper resource="com/self/dao/UserMapper.xml" />
  22. </mappers>
  23. </configuration>

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.self.dao.UserMapper">
  5. <resultMap id="userMap" type="User">
  6. <result property="id" column="user_id"/>
  7. <result property="name" column="name"/>
  8. <result property="dept" column="dept"/>
  9. <result property="phone" column="phone"/>
  10. <collection property="weibos" ofType="com.self.bean.Weibo" column="user_id">
  11. <!--<id property="id" column="t_weibo.id" javaType="int" jdbcType="INTEGER" />-->
  12. <!--不加表别名或者表名来区分id的话会导致查询不出多条数据-->
  13. <id property="id" column="p.id" javaType="int" jdbcType="INTEGER" />
  14. <result property="title" column="title" javaType="string" jdbcType="VARCHAR"/>
  15. <result property="content" column="content" javaType="string" jdbcType="VARCHAR"/>
  16. </collection>
  17. </resultMap>
  18. <select id="getUserInfoById" resultMap="userMap" parameterType="int">
  19. <!-- SELECT u.*,p.*
  20. FROM t_user u, t_weibo p
  21. WHERE u.id = p.user_id AND u.id=#{id}-->
  22. SELECT u.*,p.*
  23. FROM t_user u
  24. inner join t_weibo p on u.id = p.user_id
  25. WHERE u.id=#{id}
  26. </select>
  27. </mapper>
  28. package com.self;
  29. import com.alibaba.fastjson.JSON;
  30. import com.self.bean.User;
  31. import com.self.dao.UserMapper;
  32. import org.apache.ibatis.io.Resources;
  33. import org.apache.ibatis.session.SqlSession;
  34. import org.apache.ibatis.session.SqlSessionFactory;
  35. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  36. import java.io.IOException;
  37. import java.io.Reader;
  38. import java.math.BigDecimal;
  39. import java.util.Date;
  40. import java.util.List;
  41. /**
  42. * Copyright (C), 2015-2020, UCAR.INC
  43. * ClassName: HelloTest
  44. * Author: Rongfeng.Lai
  45. * Date: 2020/3/31 14:42
  46. * Description:
  47. * History:
  48. * <author> <time> <version> <desc>
  49. * Rongfeng.Lai 2020/3/31 v1.1.0 描述
  50. */
  51. public class HelloTest {
  52. private static SqlSessionFactory sqlSessionFactory;
  53. private static Reader reader;
  54. static {
  55. try {
  56. reader = Resources.getResourceAsReader("mybatis-config.xml");
  57. sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  58. //在sqlSessionFactory中添加Mapper
  59. //sqlSessionFactory.getConfiguration().addMapper(UserMapper.class);
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. public static SqlSessionFactory getSessionFactory(){
  65. return sqlSessionFactory;
  66. }
  67. public static void main(String[] args) {
  68. SqlSession sqlSession = getSessionFactory().openSession();
  69. try {
  70. User user = sqlSession.selectOne("com.self.dao.UserMapper.getUserInfoById", 4);
  71. System.out.println("---------"+JSON.toJSONString(user));
  72. } finally {
  73. sqlSession.close();
  74. }
  75. }
  76. }

输出:

  1. ---------{"dept":"森林矮人王国","id":4,"name":"霍恩斯","phone":"852-253521","weibos":[{"content":"由于矮人种族的原因,他无法成为龙骑士,但这并不影响他在小佣兵团以及整个人神大战中快速成为超级巨星,擅长谋略尤擅兵法让他成为矮人的异类。","id":4,"title":"霍恩斯描述"}]}

当配置resultMap时jdbcType="TEXT"会报错,要配置成jdbcType="VARCHAR"。

  1. <result property="content" column="content" javaType="string" jdbcType="TEXT"/>
  2. 报错:
  3. Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'com/self/dao/UserMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving JdbcType. Cause: java.lang.IllegalArgumentException: No enum constant org.apache.ibatis.type.JdbcType.TEXT

Mybatis表关联多对一

实例:

实体类bean不变

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <resultMap id="weiboMap" type="Weibo">
  5. <result property="id" column="id"/>
  6. <result property="title" column="title"/>
  7. <result property="content" column="content"/>
  8. <association property="user" javaType="User">
  9. <id property="id" column="user_id"/>
  10. <result property="name" column="name"/>
  11. <result property="dept" column="dept"/>
  12. <result property="mobile" column="mobile"/>
  13. </association>
  14. </resultMap>
  15. <select id="getWeiboInfoById" resultMap="weiboMap" parameterType="int">
  16. SELECT u.*,w.*
  17. FROM t_user u
  18. inner join t_weibo w on u.id = w.user_id
  19. WHERE w.id= #{id}
  20. </select>
  21. </mapper>

测试类

  1. Weibo weibo = sqlSession.selectOne("com.self.dao.UserMapper.getWeiboInfoById", 1000);
  2. System.out.println("---------"+JSON.toJSONString(weibo));

输出:

  1. ---------{"content":"史料记载中第一个神圣巨龙使骑士,在所有的文明中,他都是传统骑士准则的典范,正直、善良、忠诚、守信、怜悯等一切人类美德的拥有者。人龙神三人组合中的一人。在神界受到龙神以黄金凤的胁迫,毅然解除与冰系神圣巨龙使泰穆格尔赛的龙骑士契约,解除龙神的威胁,后与光明神同归于尽。","id":2,"title":"大青山描述","user":{"dept":"amy empire","id":2,"name":"大青山"}}

Mybatis 多对多

mybatis3.0 添加了association和collection标签专门用于对多个相关实体类数据进行级联查询,但仍不支持多个相关实体类数据的级联保存和级联删除操作。因此在进行实体类多对多映射表设计时,需要专门建立一个关联对象类对相关实体类的关联关系进行描述(映射表 user_side )。

多对多关系本质上还是一对多关系的延伸,各自是一对多关系的联系,因此变成了多对多的关系,在对单个数据处理时还是一对多关系的处理。

前提准备:

  1. CREATE TABLE `t_side` (
  2. `side_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
  3. `side_name` varchar(254) NOT NULL COMMENT '势力名称',
  4. `create_emp` bigint(20) NOT NULL COMMENT '创建人',
  5. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  6. `modify_emp` bigint(20) DEFAULT NULL COMMENT '修改人',
  7. `modify_time` datetime DEFAULT NULL COMMENT '修改时间',
  8. PRIMARY KEY (`side_id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=100 DEFAULT CHARSET=utf8 COMMENT='所属势力表';
  10. INSERT INTO `hello_mybatis`.`t_side` ( `side_name`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  11. ('艾米帝国', '10', '2020-04-01 16:36:25', '10', '2020-04-01 16:36:28');
  12. INSERT INTO `hello_mybatis`.`t_side` ( `side_name`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  13. ('哈米尔王国', '10', '2020-04-01 16:36:25', '10', '2020-04-01 16:36:28');
  14. INSERT INTO `hello_mybatis`.`t_side` ( `side_name`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  15. ('恶魔岛', '10', '2020-04-01 16:36:25', '10', '2020-04-01 16:36:28');
  16. INSERT INTO `hello_mybatis`.`t_side` ( `side_name`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  17. ('精灵王国', '10', '2020-04-01 16:36:25', '10', '2020-04-01 16:36:28');
  18. CREATE TABLE `t_user_side` (
  19. `user_id` int(10) unsigned NOT NULL COMMENT '用户id' ,
  20. `side_id` int(10) unsigned NOT NULL COMMENT '所属势力id'
  21. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT ='用户势力映射表';
  22. INSERT INTO `hello_mybatis`.`t_user_side` (`user_id`, `side_id`) VALUES ('1', '100');
  23. INSERT INTO `hello_mybatis`.`t_user_side` (`user_id`, `side_id`) VALUES ('1', '101');
  24. INSERT INTO `hello_mybatis`.`t_user_side` (`user_id`, `side_id`) VALUES ('1', '103');
  25. INSERT INTO `hello_mybatis`.`t_user_side` (`user_id`, `side_id`) VALUES ('3', '100');
  26. INSERT INTO `hello_mybatis`.`t_user_side` (`user_id`, `side_id`) VALUES ('2', '100');
  27. sql错误修改
  28. ALTER TABLE t_user_group RENAME t_user_side;
  29. ALTER TABLE t_user_side CHANGE group_id side_id int(10) unsigned NOT NULL COMMENT '所属势力id';

实例:

bean对象

  1. public class User {
  2. /**
  3. * 成员所属势力群
  4. */
  5. private List<Side> sides;
  6. /**
  7. * id
  8. */
  9. private int id;
  10. /**
  11. * 名字
  12. */
  13. private String name;
  14. /**
  15. * 部门,帝国
  16. */
  17. private String dept;
  18. /**
  19. * 联系号码
  20. */
  21. private String phone;
  22. /**
  23. * 身高
  24. */
  25. private BigDecimal height;
  26. //private List<Weibo> weibos;
  27. /**
  28. * 创建人
  29. */
  30. private Long createEmp;
  31. /**
  32. * 创建时间
  33. */
  34. private Date createTime;
  35. /**
  36. * 修改人
  37. */
  38. private Long modifyEmp;
  39. /**
  40. * 修改时间
  41. */
  42. private Date modifyTime;
  43. }
  44. public class Side {
  45. /**
  46. * 所属势力下成员
  47. */
  48. private List<User> users;
  49. /**
  50. * 所属势力id
  51. */
  52. private int sideId;
  53. /**
  54. * 所属势力名称
  55. */
  56. private String sideName;
  57. /**
  58. * 创建人
  59. */
  60. private Long createEmp;
  61. /**
  62. * 创建时间
  63. */
  64. private Date createTime;
  65. /**
  66. * 修改人
  67. */
  68. private Long modifyEmp;
  69. /**
  70. * 修改时间
  71. */
  72. private Date modifyTime;
  73. }
  74. public class UserSide {
  75. /**
  76. * 用户id
  77. */
  78. private int userId;
  79. /**
  80. * 势力id
  81. */
  82. private int sideId;
  83. }

mybatis-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <typeAliases>
  6. <typeAlias alias="User" type="com.self.bean.User" />
  7. <typeAlias type="com.self.bean.Side" alias="Side"/>
  8. <typeAlias type="com.self.bean.UserSide" alias="UserSide"/>
  9. </typeAliases>
  10. <environments default="development">
  11. <environment id="development">
  12. <transactionManager type="JDBC" />
  13. <dataSource type="POOLED">
  14. <property name="driver" value="com.mysql.jdbc.Driver" />
  15. <property name="url" value="jdbc:mysql://127.0.0.1:3306/hello_mybatis" />
  16. <property name="username" value="root" />
  17. <property name="password" value="123456" />
  18. </dataSource>
  19. </environment>
  20. </environments>
  21. <mappers>
  22. <mapper resource="com/self/dao/UserMapper.xml" />
  23. <mapper resource="com/self/dao/SideMapper.xml"/>
  24. <mapper resource="com/self/dao/UserSideMapper.xml"/>
  25. </mappers>
  26. </configuration>

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.self.dao.UserMapper">
  5. <resultMap id="userMap" type="User">
  6. <result property="id" column="id"/>
  7. <result property="name" column="name"/>
  8. <result property="phone" column="phone"/>
  9. <collection property="sides" column="user_id" select="com.self.dao.UserSideMapper.getSidesByUserId"/>
  10. </resultMap>
  11. <select id="getUserById" parameterType="int" resultMap="userMap">
  12. select * from `t_user` where id = #{id}
  13. </select>
  14. </mapper>

SideMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.self.dao.SideMapper">
  5. <resultMap id="sideMap" type="Side">
  6. <result property="sideId" column="side_id"/>
  7. <result property="sideName" column="side_name"/>
  8. <collection property="users" column="side_id" select="com.self.dao.UserSideMapper.getUsersBySideId"/>
  9. </resultMap>
  10. <select id="getSideById" parameterType="int" resultMap="sideMap">
  11. select * from `t_side` where side_id = #{sideId}
  12. </select>
  13. <insert id="insert" parameterType="Side">
  14. insert into t_side(`side_name`, `create_emp`, `create_time`, `modify_emp`, `modify_time`) VALUES
  15. (#{sideName},#{createEmp},#{createTime},#{modifyEmp},#{modifyTime})
  16. </insert>
  17. </mapper>

UserSideMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.self.dao.UserSideMapper">
  5. <resultMap id="userSideMap" type="UserSide">
  6. <result property="userId" column="user_id"/>
  7. <result property="sideId" column="side_id"/>
  8. </resultMap>
  9. <resultMap id="userMap" type="User">
  10. <result property="id" column="id"/>
  11. <result property="name" column="name"/>
  12. <result property="phone" column="phone"/>
  13. </resultMap>
  14. <resultMap id="sideMap" type="Side">
  15. <result property="sideId" column="side_id"/>
  16. <result property="sideName" column="side_name"/>
  17. <collection property="users" column="side_id" select="com.self.dao.UserSideMapper.getUsersBySideId"/>
  18. </resultMap>
  19. <select id="getSidesByUserId" resultMap="sideMap" parameterType="int">
  20. select s.* , us.user_id from t_side s inner join t_user_side us on s.side_id = us.side_id
  21. where us.user_id = #{userId}
  22. </select>
  23. <select id="getUsersBySideId" resultMap="userMap" parameterType="int">
  24. select u.* , us.side_id from t_user u inner join t_user_side us on u.id = us.user_id
  25. where us.side_id = #{sideId}
  26. </select>
  27. <insert id="insert" parameterType="UserSide">
  28. INSERT INTO t_user_side (`user_id`, `group_id`) VALUES (#{userId},#{sideId})
  29. </insert>
  30. </mapper>
  31. //测试类代码
  32. UserSideMapper us = sqlSession.getMapper(UserSideMapper.class);
  33. List<Side> sides = us.getSidesByUserId(1);
  34. StringBuilder sb = new StringBuilder();
  35. for (Side side : sides) {
  36. sb.append(side.getSideName()+", ");
  37. }
  38. System.out.println("----------该成员所属势力-------------"+sb);
  39. List<User> users = us.getUsersBySideId(100);
  40. StringBuilder sb2 = new StringBuilder();
  41. for (User user : users) {
  42. sb2.append(user.getName() + ", ");
  43. }
  44. System.out.println("----------该势力拥有的成员-------------"+sb2);

输出:

  1. ----------该成员所属势力-------------艾米帝国, 哈米尔王国, 精灵王国,
  2. ----------该势力拥有的成员-------------艾米, 池寒枫, 大青山,

报错:

1、Cannot find class: userMap 原因:

  1. Caused by: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'com/self/dao/UserMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'userMap'. Cause: java.lang.ClassNotFoundException: Cannot find class: userMap
  2. <select id="getUserById" parameterType="int" resultMap="userMap">
  3. select * from `t_user` where id = #{id}
  4. </select>
  5. <!-- 自定义的bean实例类型要指定resultMapresultType普通bean用的-->
  6. <select id="getUserById" parameterType="int" resultType="userMap">
  7. select * from `t_user` where id = #{id}
  8. </select>

Mybatis与Spring集成

框架搭建的核心就是配置文件。

实例:

pom.xml依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <version>4.11</version>
  6. <scope>test</scope>
  7. </dependency>
  8. <!--=================mybatis框架依赖===============-->
  9. <dependency>
  10. <groupId>org.mybatis</groupId>
  11. <artifactId>mybatis</artifactId>
  12. <version>3.4.6</version>
  13. </dependency>
  14. <dependency>
  15. <groupId>mysql</groupId>
  16. <artifactId>mysql-connector-java</artifactId>
  17. <version>5.1.31</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.junit.jupiter</groupId>
  21. <artifactId>junit-jupiter-api</artifactId>
  22. <version>RELEASE</version>
  23. <scope>compile</scope>
  24. </dependency>
  25. <!--=================mybatis框架依赖===============-->
  26. <dependency>
  27. <groupId>com.alibaba</groupId>
  28. <artifactId>fastjson</artifactId>
  29. <version>1.2.60</version>
  30. </dependency>
  31. <!--=================mybatis整合spring依赖===============-->
  32. <dependency>
  33. <groupId>org.mybatis</groupId>
  34. <artifactId>mybatis-spring</artifactId>
  35. <version>1.3.2</version>
  36. </dependency>
  37. <!--=================mybatis整合spring依赖===============-->
  38. <!--=================spring依赖===============-->
  39. <dependency>
  40. <groupId>org.springframework</groupId>
  41. <artifactId>spring-context</artifactId>
  42. <version>4.3.8.RELEASE</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework</groupId>
  46. <artifactId>spring-tx</artifactId>
  47. <version>3.2.7.RELEASE</version>
  48. </dependency>
  49. <dependency>
  50. <groupId>org.springframework</groupId>
  51. <artifactId>spring-jdbc</artifactId>
  52. <version>3.1.3.RELEASE</version>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.springframework</groupId>
  56. <artifactId>spring-beans</artifactId>
  57. <version>4.3.8.RELEASE</version>
  58. </dependency>
  59. <dependency>
  60. <groupId>org.springframework</groupId>
  61. <artifactId>spring-core</artifactId>
  62. <version>4.3.8.RELEASE</version>
  63. </dependency>
  64. <dependency>
  65. <groupId>org.apache.commons</groupId>
  66. <artifactId>commons-lang3</artifactId>
  67. <version>3.8.1</version>
  68. </dependency>
  69. <dependency>
  70. <groupId>org.springframework</groupId>
  71. <artifactId>spring-web</artifactId>
  72. <version>4.0.9.RELEASE</version>
  73. </dependency>
  74. <dependency>
  75. <groupId>org.springframework</groupId>
  76. <artifactId>spring-webmvc</artifactId>
  77. <version>4.0.9.RELEASE</version>
  78. </dependency>
  79. <!--=================spring依赖===============-->
  80. <!--=================切面依赖===============-->
  81. <dependency>
  82. <groupId>org.springframework</groupId>
  83. <artifactId>spring-aop</artifactId>
  84. <version>4.3.8.RELEASE</version>
  85. </dependency>
  86. <dependency>
  87. <groupId>org.aspectj</groupId>
  88. <artifactId>aspectjweaver</artifactId>
  89. <version>1.9.2</version>
  90. </dependency>
  91. <!--=================切面依赖===============-->
  92. </dependencies>

web.xml 配置spring 和springmvc容器

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  5. http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  6. version="3.1">
  7. <servlet>
  8. <servlet-name>hellomybatis</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <init-param>
  11. <param-name>contextConfigLocation</param-name>
  12. <param-value>
  13. WEB-INF/hellomybatis-servlet.xml
  14. </param-value>
  15. </init-param>
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>hellomybatis</servlet-name>
  20. <url-pattern>/</url-pattern>
  21. </servlet-mapping>
  22. <context-param>
  23. <param-name>contextConfigLocation</param-name>
  24. <param-value>classpath*:applicationContext.xml</param-value>
  25. </context-param>
  26. <listener>
  27. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  28. </listener>
  29. </web-app>

hellomybatis-servlet.xml springmvc配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:tx="http://www.springframework.org/schema/tx"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
  9. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop.xsd
  14. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
  15. <!--spring mvc容器扫描配置-->
  16. <context:component-scan base-package="com.self" use-default-filters="false">
  17. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  18. </context:component-scan>
  19. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  20. <property name="prefix" value="/WEB-INF/jsp/"/>
  21. <property name="suffix" value=".jsp"/>
  22. </bean>
  23. </beans>

applicationContext.xml spring配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:tx="http://www.springframework.org/schema/tx"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
  9. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop.xsd
  14. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
  15. <!--spring 容器扫描配置-->
  16. <context:component-scan base-package="com.self">
  17. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  18. </context:component-scan>
  19. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  20. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  21. <property name="url" value="jdbc:mysql://localhost:3306/hello_mybatis"/>
  22. <property name="username" value="root"/>
  23. <property name="password" value="123456"/>
  24. </bean>
  25. <!-- 添加事务支持 -->
  26. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  27. <property name="dataSource" ref="dataSource"/>
  28. </bean>
  29. <!-- 注册事务管理驱动 表示支持声明式事务 @Transactional 注解标注的会被代理实现事务,但要用在有接口的public方法中-->
  30. <!--基于注解的方式使用事务配置声明-->
  31. <tx:annotation-driven transaction-manager="transactionManager" />
  32. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  33. <!--dataSource连接池-->
  34. <property name="dataSource" ref="dataSource"/>
  35. <!--configLocation属性指定mybatis的核心配置文件-->
  36. <!--如果想把下面整个mybatis-config.xml文件property注释删除了,那么在 UserMapper.xml 这些文件里的type就要配置成全路径的格式如com.self.bean.Side
  37. 否则会找不到bean-->
  38. <property name="configLocation" value="classpath:mybatis-config.xml"/>
  39. <!-- 所有配置的mapper文件 该配置相当于是mybatis-config.xml里的mappers配置,在这边直接扫描获取了-->
  40. <property name="mapperLocations" value="classpath*:com/self/dao/*.xml"/>
  41. <!--typeAliasesPackage:批量别名处理 通过这些property就可以把mybatis-config.xml替代掉了-->
  42. <property name="typeAliasesPackage" value="com.self.bean"/>
  43. </bean>
  44. <!-- Mapper代理开发,使用Spring自动扫描MyBatis的接口并装配 (Spring将指定包中的所有被@Mapper注解标注的接口自动装配为MyBatis的映射接口) -->
  45. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  46. <!-- mybatis-spring组件的扫描器(UserMapper.java),com.dao只需要接口(接口方法与SQL映射文件中的相同) -->
  47. <property name="basePackage" value="com.self.dao"/>
  48. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  49. </bean>
  50. </beans>

mybatis-config.xml mybaits配置文件可以不写了

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <!--mybatis-config.xml可以不用配置,直接通过扫描来配置mapper-->
  6. <!-- <typeAliases>
  7. <typeAlias alias="User" type="com.self.bean.User" />
  8. <typeAlias type="com.self.bean.Side" alias="Side"/>
  9. <typeAlias type="com.self.bean.UserSide" alias="UserSide"/>
  10. <typeAlias type="com.self.bean.Weibo" alias="Weibo"/>
  11. </typeAliases>-->
  12. <!--
  13. <environments default="development">
  14. <environment id="development">
  15. <transactionManager type="JDBC" />
  16. <dataSource type="POOLED">
  17. <property name="driver" value="com.mysql.jdbc.Driver" />
  18. <property name="url" value="jdbc:mysql://127.0.0.1:3306/hello_mybatis" />
  19. <property name="username" value="root" />
  20. <property name="password" value="123456" />
  21. </dataSource>
  22. </environment>
  23. </environments>
  24. -->
  25. <!-- <mappers>
  26. <mapper resource="com/self/dao/UserMapper.xml" />
  27. <mapper resource="com/self/dao/SideMapper.xml"/>
  28. <mapper resource="com/self/dao/UserSideMapper.xml"/>
  29. </mappers>-->
  30. </configuration>

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <select id="getUsers" resultType="User">
  5. select * from `t_user` where 1 = 1
  6. </select>
  7. </mapper>
  8. @Repository
  9. //@Mapper
  10. public interface UserMapper {
  11. public List<User> getUsers();
  12. }
  13. public interface UserService {
  14. public List<User> getUsers();
  15. }
  16. @Service("userService")
  17. public class UserServiceImpl implements UserService {
  18. @Override
  19. public List<User> getUsers() {
  20. return userMapper.getUsers();
  21. }
  22. }
  23. @Controller
  24. public class UserController {
  25. @Autowired
  26. private UserService userService;
  27. @RequestMapping("/user")
  28. public void getUsers(){
  29. System.out.println(JSON.toJSONString(userService.getUsers()));
  30. }
  31. }

输出:

  1. [{"dept":"amy empire","height":1.75,"id":1,"name":"艾米","phone":"18956563228"},{"dept":"amy empire","height":1.85,"id":2,"name":"大青山","phone":"18956563229"},{"dept":"amy empire","height":1.83,"id":3,"name":"池寒枫","phone":"22056545"},{"dept":"森林矮人王国","height":1.56,"id":4,"name":"霍恩斯","phone":"852-253521"}]

报错:

1、@RequestMapping("/user") 注解用不了。

  1. <!--=================需要依赖 spring-web===============-->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-web</artifactId>
  5. <version>4.0.9.RELEASE</version>
  6. </dependency>

2、import不了DispatcherServlet

  1. <!--=================需要依赖 spring-webmvc===============-->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-webmvc</artifactId>
  5. <version>4.0.9.RELEASE</version>
  6. </dependency>

3、No bean named 'userController' available,找不到bean。报这个错是因为使用容器扫描配置时注释了过滤的Controller类型,但是没有把use-default-filters="false" 配置删了,倒置没有过滤的Controller配置的话,那么默认是全部过滤,就没有bean实例被扫描进去了。要改成下面这样。

  1. Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userController' available
  2. at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
  3. at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
  4. <!--spring 容器扫描配置 错误配置-->
  5. <context:component-scan base-package="com.self" use-default-filters="false">
  6. <!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
  7. </context:component-scan>
  8. <!--spring 容器扫描配置 正确配置-->
  9. <context:component-scan base-package="com.self" >
  10. </context:component-scan>

context:component-scan除了具有context:annotation-config的功能之外,context:component-scan还可以在指定的package下扫描以及注册javabean 。还具有自动将带有@component,@service,@Repository等注解的对象注册到spring容器中的功能。

因此当使用 context:component-scan 后,就可以将 context:annotation-config移除。

4、Result Maps collection already contains value for com.self.dao.SideMapper.sideMap .集合容器里已经有该类型的值了。这个报错是因为当配置了mybatis-config.xml文件的mappers的同时还注册了MapperScannerConfigurer 的自动扫描MyBatis的接口并装配。注册了两遍。因此只要配置一个就行了,我这边是把mybatis-config.xml文件注释掉了。

  1. Caused by: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [F:\self\hellomybatis\target\classes\com\self\dao\SideMapper.xml]'. Cause: java.lang.IllegalArgumentException: Result Maps collection already contains value for com.self.dao.SideMapper.sideMap
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!--mybatis-config.xml可以不用配置,直接通过扫描来配置mapper-->
  7. <!-- <typeAliases>
  8. <typeAlias alias="User" type="com.self.bean.User" />
  9. <typeAlias type="com.self.bean.Side" alias="Side"/>
  10. <typeAlias type="com.self.bean.UserSide" alias="UserSide"/>
  11. <typeAlias type="com.self.bean.Weibo" alias="Weibo"/>
  12. </typeAliases>-->
  13. <!--
  14. <environments default="development">
  15. <environment id="development">
  16. <transactionManager type="JDBC" />
  17. <dataSource type="POOLED">
  18. <property name="driver" value="com.mysql.jdbc.Driver" />
  19. <property name="url" value="jdbc:mysql://127.0.0.1:3306/hello_mybatis" />
  20. <property name="username" value="root" />
  21. <property name="password" value="123456" />
  22. </dataSource>
  23. </environment>
  24. </environments>
  25. -->
  26. <!-- <mappers>
  27. <mapper resource="com/self/dao/UserMapper.xml" />
  28. <mapper resource="com/self/dao/SideMapper.xml"/>
  29. <mapper resource="com/self/dao/UserSideMapper.xml"/>
  30. </mappers>-->
  31. </configuration>

5、Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'。注册userControllerbean时依赖的userService不能得到的注入。

这个原因还是出在spring 容器扫描配置配置上,use-default-filters="false" 使用不当。

  1. org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.self.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  2. <!--spring 容器扫描配置-->
  3. <context:component-scan base-package="com.self" use-default-filters="false">
  4. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  5. </context:component-scan>
  6. <!--spring 容器扫描配置-->
  7. <context:component-scan base-package="com.self">
  8. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
  9. </context:component-scan>

use-default-filters 属性的默认值为 true,即使用默认的 Filter 进行包扫描,而默认的 Filter 对标有 @Service,@Controller和@Repository 的注解的类进行扫描。设置为 false,即不使用默认的 Filter 进行扫描。也就是不扫描,只扫描下面配置的include-filter,下面配置的扫描注解有几个就只扫几个,有一个就扫一个。

我们希望 SpringMVC容器 只来控制网站的跳转逻辑,所以我们只希望 SpringMVC 的配置扫描 @Controllerce 注解标注的类,不希望它扫描其余注解标注的类,所以设置了 use-default-filters 为 false,并使用 context:include-filter 子标签设置其只扫描带有 @Controller 注解标注的类。

Spring 容器就不同了,我们希望 Spring 只不扫描带有 @Controller 注解标注的类,而扫描其他注解标注的类,而这时建立在使用默认的 Filter 进行扫描的基础上,设置了 context:exclude-filter 标签,不扫描 @Controller 注解标注的类,所以不应该设置 use-default-filters 为 false 。

use-default-filters="false" 需要和 context:include-filter 一起使用,而不能和 context:exclude-filter 属性一起使用。

参考

MyBatis分页

分页可以分为逻辑分页和物理分页。

逻辑分页是我们的程序在显示每页的数据时,首先查询得到表中的1000条数据,然后根据当前页的“页码”选出其中的100条数据来显示。 物理分页是程序先判断出该选出这1000条的第几条到第几条,然后数据库根据程序给出的信息查询出程序需要的100条返回给我们的程序。

分页待学习其他的方法,这个不好。

MyBatis动态SQL语句

mybatis 的动态sql语句是基于OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:

  1. if 语句 (简单的条件判断)

  2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.

  3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)

  4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)

  5. set (主要用于更新时)

  6. foreach (在实现 mybatis in 语句查询时特别有用)

    1. <select id="getUsersByCond" resultType="User" parameterType="User">
    2. select * from `t_user` where 1 = 1
    3. <if test="name != null">
    4. and name = #{name}
    5. </if>
    6. <if test="phone != null">
    7. and phone = #{phone}
    8. </if>
    9. <if test="author != null and author.name != null">
    10. AND author_name like #{author.name}
    11. </if>
    12. </select>

    select * from `t_user` where 1 = 1

    AND name like #{name}

    and phone = #{phone}

    and dept = #{dept}

    1. <select id="getUsersByCondition" resultType="User" parameterType="User">
    2. select * from `t_user`
    3. <where>
    4. <if test="name != null">
    5. and name = #{name}
    6. </if>
    7. <if test="phone != null">
    8. and phone = #{phone}
    9. </if>
    10. <if test="dept != null">
    11. and dept = #{dept}
    12. </if>
    13. </where>
    14. </select>

    1. <select id="getUsersByCondition" resultType="User" parameterType="User">
    2. select * from `t_user`
    3. <trim prefix="where" prefixOverrides="and|or">
    4. <if test="name != null">
    5. and name = #{name}
    6. </if>
    7. <if test="phone != null">
    8. and phone = #{phone}
    9. </if>
    10. <if test="dept != null">
    11. and dept = #{dept}
    12. </if>
    13. </trim>
    14. </select>

    1. <update id="update" parameterType="User">
    2. update t_user
    3. <set>
    4. <if test="name != null">
    5. name = #{name},
    6. </if>
    7. <if test="dept != null">
    8. dept = #{dept},
    9. </if>
    10. <if test="phone != null">
    11. phone = #{phone},
    12. </if>
    13. <if test="height != null">
    14. height = #{height},
    15. </if>
    16. <if test="modifyEmp != null">
    17. modify_emp = #{modifyEmp},
    18. </if>
    19. <if test="modifyTime != null">
    20. modify_time = #{modifyTime},
    21. </if>
    22. </set>
    23. where id = #{id}
    24. </update>

    update t_user

    name = #{name},

    dept = #{dept},

    phone = #{phone},

    height = #{height},

    modify_emp = #{modifyEmp},

    modify_time = #{modifyTime},

    where id = #{id}

    select * from `t_user`

    and name = #{name}

    and phone = #{phone}

    and dept = #{dept}

    and id in

    #{id}

    1. <select id="getUsersByCondition" resultType="User" parameterType="User">
    2. <bind name="deptBlur" value="'%' + dept + '%'"></bind>
    3. select * from `t_user`
    4. <where>
    5. <if test="name != null">
    6. and name = #{name}
    7. </if>
    8. <if test="phone != null">
    9. and phone = #{phone}
    10. </if>
    11. <if test="dept != null">
    12. and dept like #{deptBlur}
    13. </if>
    14. <if test="ids != null">
    15. and id in
    16. <foreach collection="ids" item="id" open="(" close=")" separator=",">
    17. #{id}
    18. </foreach>
    19. </if>
    20. </where>
    21. </select>

    insert id="insert">





    select seq_users.nextval from dual





    select nextval for seq_users from sysibm.sysdummy1"





    insert into users values (#{id}, #{name})

prefixOverrides使用参考

foreach查询的写法

  1. public class User {
  2. /**
  3. * 成员所属势力群
  4. */
  5. private List<Side> sides;
  6. /**
  7. * id
  8. */
  9. private int id;
  10. private List<Integer> ids;
  11. private Integer[] idsArr;
  12. /**
  13. * 名字
  14. */
  15. private String name;
  16. /**
  17. * 部门,帝国
  18. */
  19. private String dept;
  20. /**
  21. * 联系号码
  22. */
  23. private String phone;
  24. /**
  25. * 身高
  26. */
  27. private BigDecimal height;
  28. //private List<Weibo> weibos;
  29. /**
  30. * 创建人
  31. */
  32. private Long createEmp;
  33. /**
  34. * 创建时间
  35. */
  36. private Date createTime;
  37. /**
  38. * 修改人
  39. */
  40. private Long modifyEmp;
  41. /**
  42. * 修改时间
  43. */
  44. private Date modifyTime;
  45. public Integer[] getIdsArr() {
  46. return idsArr;
  47. }
  48. public void setIdsArr(Integer[] idsArr) {
  49. this.idsArr = idsArr;
  50. }
  51. public List<Integer> getIds() {
  52. return ids;
  53. }
  54. public void setIds(List<Integer> ids) {
  55. this.ids = ids;
  56. }
  57. }

测试类:

  1. User user = new User();
  2. Integer[] idsArr = {1,2,3,4};
  3. user.setIdsArr(idsArr);
  4. user.setDept("amy empire");
  5. uc.getUserCondition(user);
  6. //===============================================
  7. User user = new User();
  8. List<Integer> ids = new ArrayList<>();
  9. ids.add(1);
  10. ids.add(2);
  11. ids.add(3);
  12. user.setIds(ids);
  13. user.setDept("amy empire");
  14. uc.getUserCondition(user);

mybaits if标签语句

实例:

  1. <select id="getUsersByCondition" resultType="User" parameterType="User">
  2. select * from `t_user`
  3. <where>
  4. <if test="name != null and name !='' ">
  5. and name = #{name,jdbcType=VARCHAR}
  6. </if>
  7. <if test="phone != null and phone !='' ">
  8. and phone = #{phone,jdbcType=VARCHAR}
  9. </if>
  10. <if test="dept != null and dept != '' ">
  11. <!-- 另外一种模糊查询%的拼接方法 -->
  12. and dept like CONCAT(CONCAT('%', #{dept,jdbcType=VARCHAR}),'%')
  13. </if>
  14. <if test="ids != null">
  15. and id in
  16. <foreach collection="ids" item="id" open="(" close=")" separator=",">
  17. #{id}
  18. </foreach>
  19. </if>
  20. </where>
  21. </select>

错误:

里的连接词 and 不能大写,否则会识别不了,要用小写的and。因为mybatis区分大小写,and是约定的关键字,应该用小写的and。

  1. Exception in thread "main" org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.builder.BuilderException: Error evaluating expression 'name != null AND name !='' '. Cause: org.apache.ibatis.ognl.ExpressionSyntaxException: Malformed OGNL expression: name != null AND name !='' [org.apache.ibatis.ognl.ParseException: Encountered " <IDENT> "AND "" at line 1, column 14.
  2. Was expecting one of:
  3. <if test="phone != null and phone !='' ">
  4. AND phone = #{phone,jdbcType=VARCHAR}
  5. </if>
  6. <!-- 下面才是正确写法 -->
  7. <if test="phone != null and phone !='' ">
  8. and phone = #{phone,jdbcType=VARCHAR}
  9. </if>

!和= 之间多了一个空格也会报错,if test="phone ! = null and phone ! ='' 。应该去掉空格

  1. <!-- 下面才是正确写法 -->
  2. <if test="phone != null and phone !='' ">
  3. and phone = #{phone}
  4. </if>

MyBatis where标签语句

“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 AND 或OR 开头的,则它会剔除掉。

Mybatis set标签

当 update 语句中没有使用 if 标签时,如果有一个参数为 null,都会导致错误。

  1. 当在 update 语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置 SET 关键字,并剔除追加到条件末尾的任何不相关的逗号。使用 if+set 标签修改后,如果某项为 null 则不进行更新,而是保持数据库原值。

报错:如果 set 包含的内容为空的话则会出错 ,如下。

  1. update t_user where id = ?
  2. ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where id = 2' at line 3
  3. ;

Mybatis trim标签

trim 是更灵活用来去处多余关键字的标签,它可以用来实现 where 和 set 的效果。trim 元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是 prefix 和 suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是 prefixOverrides 和 suffixOverrides;正因为 trim 有这样的功能,所以我们也可以非常简单的利用 trim 来代替 where 元素的功能。

choose (when, otherwise)标签

有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为 true,就会执行 if 标签中的条件。MyBatis 提供了 choose 元素。if标签是与(and)的关系,而 choose 是或(or)的关系。

  1. choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java switch 语句,choose switchwhen caseotherwise 则为 default

MyBatis SqlSessionDaoSupport实例

待验证。没用

MyBatis打印输出SQL语句

实例:

log4j.properties

  1. log4j.rootLogger=debug,stdout,logfile
  2. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  3. #log4j.appender.stdout.Target=System.err
  4. log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
  5. log4j.appender.logfile=org.apache.log4j.FileAppender
  6. log4j.appender.logfile.File=C:/mybatis_show_sql.log
  7. log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
  8. log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
  9. log4j.logger.com.ibatis=DEBUG
  10. log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
  11. log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
  12. log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
  13. log4j.logger.java.sql.Connection=DEBUG
  14. log4j.logger.java.sql.Statement=DEBUG
  15. log4j.logger.java.sql.PreparedStatement=DEBUG

pom.xml依赖

  1. <dependency>
  2. <groupId>org.slf4j</groupId>
  3. <artifactId>slf4j-api</artifactId>
  4. <version>1.7.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>log4j</groupId>
  8. <artifactId>log4j</artifactId>
  9. <version>1.2.17</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.slf4j</groupId>
  13. <artifactId>slf4j-log4j12</artifactId>
  14. <version>1.7.21</version>
  15. </dependency>

输出:

  1. DEBUG - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@647f63b4] was not registered for synchronization because synchronization is not active
  2. DEBUG - Fetching JDBC Connection from DataSource
  3. DEBUG - Creating new JDBC DriverManager Connection to [jdbc:mysql://localhost:3306/hello_mybatis]
  4. DEBUG - JDBC Connection [com.mysql.jdbc.JDBC4Connection@481b3df0] will not be managed by Spring
  5. DEBUG - ==> Preparing: select * from `t_user` WHERE id in ( ? , ? , ? )
  6. DEBUG - ==> Parameters: 1(Integer), 2(Integer), 3(Integer)
  7. DEBUG - <== Total: 3
  8. DEBUG - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@647f63b4]
  9. DEBUG - Returning JDBC Connection to DataSource
  10. ERROR - [{"dept":"amy empire","height":1.75,"id":1,"name":"大青山","phone":"18956563228"},{"dept":"amy empire","height":1.85,"id":2,"name":"艾米哈珀","phone":"18956563228"},{"dept":"amy empire","height":1.83,"id":3,"name":"池寒枫","phone":"22056545"}]

疑问:

Q:什么是OGNL表达式?

A:对象导航图语言(Object Graph Navigation Language),简称OGNL,是应用于Java中的一个开源的表达式语言(Expression Language),它被集成在mybatis等框架中,作用是对数据进行访问,它拥有类型转换、访问对象方法、操作集合对象等功能。

Q:像下面这种变量要怎么配置各个环境的变量,方便替换,怎么读取到相应的properties文件?value="${driver}"

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <environments default="development">
  7. <environment id="development">
  8. <transactionManager type="JDBC"/>
  9. <dataSource type="POOLED">
  10. <property name="driver" value="${driver}"/>
  11. <property name="url" value="${url}"/>
  12. <property name="username" value="${username}"/>
  13. <property name="password" value="${password}"/>
  14. </dataSource>
  15. </environment>
  16. </environments>
  17. <mappers>
  18. <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  19. </mappers>
  20. </configuration>

Q:MyBatis ofType和javaType区别?

A:JavaType和ofType都是用来指定对象类型的,但是JavaType是用来指定pojo中属性的类型,而ofType指定的是映射到list集合属性中pojo的类型。

Q:下面两个resultMap有什么区别么?为什么要多指导jdbcType 和javaType,去掉这两个后运行程序还是正常,那这两个有什么作用?

  1. <resultMap id="userMap" type="User">
  2. <result property="id" column="user_id"/>
  3. <result property="name" column="name"/>
  4. <result property="dept" column="dept"/>
  5. <result property="phone" column="phone"/>
  6. <collection property="weibos" ofType="com.self.bean.Weibo" column="user_id">
  7. <!--<id property="id" column="t_weibo.id" javaType="int" jdbcType="INTEGER" />-->
  8. <!--不加表别名或者表名来区分id的话会导致查询不出多条数据-->
  9. <id property="id" column="p.id" />
  10. <result property="title" column="title" />
  11. <result property="content" column="content" />
  12. </collection>
  13. </resultMap>
  14. <!--===========================分割===========================-->
  15. <resultMap id="userMap" type="User">
  16. <result property="id" column="user_id"/>
  17. <result property="name" column="name"/>
  18. <result property="dept" column="dept"/>
  19. <result property="phone" column="phone"/>
  20. <collection property="weibos" ofType="com.self.bean.Weibo" column="user_id">
  21. <!--<id property="id" column="t_weibo.id" javaType="int" jdbcType="INTEGER" />-->
  22. <!--不加表别名或者表名来区分id的话会导致查询不出多条数据-->
  23. <id property="id" column="p.id" javaType="int" jdbcType="INTEGER" />
  24. <result property="title" column="title" javaType="string" jdbcType="VARCHAR"/>
  25. <result property="content" column="content" javaType="string" jdbcType="VARCHAR"/>
  26. </collection>
  27. </resultMap>

Q:@Mapper注解的作用是什么?

  1. @Mapper
  2. public interface UserMapper {}

Q:在写mybatissql时为什么查询绑定的值还要指定上jdbcType类型呢?不写也是可以的,写和不写的区别?如下

  1. and phone = #{phone,jdbcType=VARCHAR}

Q:有空研究下log4j.properties上的具体配置如何操作,自定义,形成文档。

MyBatis 教程 ——检视阅读的更多相关文章

  1. AJAX教程——检视阅读

    AJAX教程--检视阅读 参考 AJAX 教程--菜鸟 AJAX 教程--w3cschool AJAX 教程--w3school.cn AJAX 教程--易百 AJAX = Asynchronous ...

  2. Spring MVC教程——检视阅读

    Spring MVC教程--检视阅读 参考 Spring MVC教程--一点--蓝本 Spring MVC教程--c语言中午网--3.0版本太老了 Spring MVC教程--易百--4.0版本不是通 ...

  3. SpringBoot教程——检视阅读

    SpringBoot教程--检视阅读 参考 SpringBoot教程--一点--蓝本--springboot2.1.1 SpringBoot教程--易百--springboo2.0.5.RELEASE ...

  4. Spring教程检视阅读

    Spring教程检视阅读 地址 可供参考的教程 <菜鸟学 SSH> <Spring Boot 那些事> <初识 Spring Security> <Sprin ...

  5. MySQL 教程--检视阅读

    MySQL 教程--检视阅读 准备:Windows 上安装 MySQL 教程地址,PHP语言基础 教程地址2 教程地址3,有讲数据库的备份和恢复 教程地址4,w3c.china,php基础,扩展阅读 ...

  6. NIO教程 ——检视阅读

    NIO教程 --检视阅读 参考 BIO,NIO,AIO 总结 Java NIO浅析 Java NIO 教程--极客,蓝本 Java NIO 系列教程 --并发编程网 BIO,NIO--知乎 NIO 入 ...

  7. JDBC教程——检视阅读

    JDBC教程--检视阅读 参考 JDBC教程--W3Cschool JDBC教程--一点教程,有高级部分 JDBC教程--易百 JDBC入门教程 – 终极指南 略读 三层架构详解,JDBC在数据访问层 ...

  8. Java Web教程——检视阅读

    Java Web教程--检视阅读 参考 java web入门--概念理解.名词解释 Java Web 教程--w3school 蓝本 JavaWeb学习总结(一)--JavaWeb开发入门 小猴子mo ...

  9. Servlet 教程——检视阅读

    Servlet 教程--检视阅读 参考 Servlet教程--菜鸟--蓝本 Servlet教程--w3cschool Servlet教程--易百 servlet依赖maven依赖: <!--se ...

随机推荐

  1. Immer.js简析

    开始 在函数式编程中,Immutable这个特性是相当重要的,但是在Javascript中很明显是没办法从语言层面提供支持,但是还有其他库(例如:Immutable.js)可以提供给开发者用上这样的特 ...

  2. JS动画之缓动函数分析及动画库

    上一篇讲了JS动画定时器相关知识,这一篇介绍下缓动函数及流行的动画库. 熟悉的图 实际使用 jquery animate()+jquery.easing插件的使用: $(selector).anima ...

  3. Yuchuan_Linux_C编程之五gdb调试

    一.整体大纲 二.gdb调试 1. 启动gdb start -- 只执行一步    n -- next    s -- step(单步) -- 可以进入到函数体内部    c - continue - ...

  4. Java Opencv 实现 中值滤波器

    原理 Note 以下原理来源于Richard Szeliski 的著作 Computer Vision: Algorithms and Applications 以及 Learning OpenCV ...

  5. seo搜索优化教程12-网站SEO诊断

    为了使大家更方便的了解及学习网络营销推广.seo搜索优化,星辉信息科技强势推出seo搜索优化教程.此为seo教程第12课 行业分析 在搜索引擎中检索自己的站点,在检索结果及相关网站中分析自己在行业内的 ...

  6. http2 技术整理 nginx 搭建 http2 wireshark 抓包分析 server push 服务端推送

    使用 nginx 搭建一个 http2 的站点,准备所需: 1,域名 .com .net 均可(国内域名需要 icp 备案) 2,云主机一个,可以自由的安装配置软件的服务器 3,https 证书 ht ...

  7. 代号为 Kyria 的 Manjaro Linux 19.0 系统正式发布

    Xfce版本仍然是主打,此版本Xfce更新到4.14,并且主要致力于在桌面和窗口管理器上完善用户体验. KDE版本提供了功能强大.成熟且丰富的Plasma 5.17桌面环境,此版本进行了完全重新设计. ...

  8. CSS的SVG学习

    SVG 意为可缩放矢量图形(Scalable Vector Graphics). HTML三种方法导入svg文件: <html xmlns:svg="http://www.w3.org ...

  9. S3C2440A特殊寄存器

    S3C2440A特殊寄存器 特殊寄存器有: 输入输出端口 存储器控制器 NANDFLASH 看门狗定时器 时钟和电源管理 PWM定时器 UART USB设备 中断控制器 DMA LCD控制器 RTC ...

  10. 分享几个 PHP 编码的最佳实践

    对于初学者而言,可能很难理解为什么某些做法更安全. 但是,以下一些技巧可能超出了 PHP 的范围. 始终使用大括号 让我们看下面的代码: if (isset($condition) && ...