1.Mybatis的快速入门

1.1 MyBatis开发步骤

MyBatis官网地址:http://www.mybatis.org/mybatis-3/

MyBatis开发步骤:
项目架构:
image.png

  • 添加MyBatis的坐标
  • 创建user数据表
  • 编写User实体类 (domain.User)
  • 编写UserMapper接口 (mapper.UserMapper)
  • 编写Mybatis工具类(utils.MybatisUtil)
  • 编写映射文件UserMapper.xml
  • 编写核心文件SqlMapConfig.xml
  • 编写测试类

    1.2 环境搭建

1)导入MyBatis的坐标和其他相关坐标

  1. <!--mybatis坐标-->
  2. <dependency>
  3. <groupId>org.mybatis</groupId>
  4. <artifactId>mybatis</artifactId>
  5. <version>3.4.5</version>
  6. </dependency>
  7. <!--mysql驱动坐标-->
  8. <dependency>
  9. <groupId>mysql</groupId>
  10. <artifactId>mysql-connector-java</artifactId>
  11. <version>5.1.6</version>
  12. <scope>runtime</scope>
  13. </dependency>
  14. <!--单元测试坐标-->
  15. <dependency>
  16. <groupId>junit</groupId>
  17. <artifactId>junit</artifactId>
  18. <version>4.12</version>
  19. <scope>test</scope>
  20. </dependency>
  21. <!--日志坐标-->
  22. <dependency>
  23. <groupId>log4j</groupId>
  24. <artifactId>log4j</artifactId>
  25. <version>1.2.12</version>
  26. </dependency>
  1. 创建user数据表 ```sql create database mybatis; use mybatis;

create table user( id int(20) auto_increment not null, name varchar(30) default null, pwd varchar(30) default null, primary key (id) )engine = InnoDB default charset = utf8;

drop table user2;

insert into user (id, name, pwd) VALUES (1,’youxi’,’123456’); insert into user (name, pwd) VALUES (‘youxi2’,’123456’);

  1. 3. User实体
  2. ```java
  3. public class User {
  4. private int id;
  5. private String username;
  6. private String password;
  7. //省略get和set方法
  8. }
  1. UserMapper( 面向接口编程,方便后续调用session.getMapper(UserMapper.class) )
  1. public interface UserMapper {
  2. // 查询所有
  3. List<User> findAll();
  4. // 根据ID查询
  5. User findById(int id);
  6. // 插入User
  7. int addUser(User user);
  8. // 根据ID删除
  9. int delUserById(int id);
  10. // 修改
  11. int updateUser(User user);
  12. // 模糊查询
  13. List<User> getUserLike(String value);
  14. // 使用map参数
  15. int addUser2(Map<String,Object> map);
  16. }
  1. UserMapper映射文件(UserMapper.xml)
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <!-- 这个namespave命名空间指向的是创建的那个UserMapper接口 -->
  6. <mapper namespace="mapper.UserMapper">
  7. <!-- 查询所有 -->
  8. <select id="findAll" resultType="pojo.User">
  9. select * from user;
  10. </select>
  11. <!-- 根据id查询 -->
  12. <select id="findById" parameterType="int" resultType="pojo.User">
  13. select * from user where id = #{id};
  14. </select>
  15. <!-- 插入 -->
  16. <insert id="addUser" parameterType="pojo.User">
  17. insert into user (id, name, pwd) values (#{id}, #{name}, #{pwd});
  18. </insert>
  19. <!-- 删除 -->
  20. <delete id="delUserById" parameterType="int">
  21. delete from user where id=#{id};
  22. </delete>
  23. <!-- 修改 -->
  24. <update id="updateUser" parameterType="pojo.User">
  25. update user set name=#{name},pwd=#{pwd} where id=#{id};
  26. </update>
  27. <!-- 模糊查询 -->
  28. <select id="getUserLike" resultType="User">
  29. select * from user where name like #{value};
  30. </select>
  31. <!-- 使用ResultMap结果集映射 -->
  32. <resultMap id="UserMap" type="User">
  33. <!-- column数据库中的字段,property实体类中的属性 -->
  34. <!-- User.java这个实体类中是password名属性 -->
  35. <result column="pwd" property="password"/>
  36. </resultMap>
  37. <select id="getUserById" resultMap="UserMap">
  38. select * from user where id=#{id};
  39. </select>
  40. <!-- 使用map参数,优点:使用map你需要什么参数就put什么参数,不需要像实体类那样new一个需要写出去全部属性-->
  41. <insert id="addUser2" parameterType="map">
  42. insert into user (id, pwd) values (#{userId}, #{passWord});
  43. </insert>
  44. </mapper>
  1. 编写MyBatis核心文件(sqlMapConfig.xml)及datasource配置文件(db.properties)

    db.properties

    1. driver=com.mysql.jdbc.Driver
    2. url=jdbc:mysql://localhost:3306/mybatis
    3. username=root
    4. password=root

    sqlMapConfig.xml

    1. <!DOCTYPE configuration
    2. PUBLIC "-//mybatis.org//DTD Config 3.0//EN“ "http://mybatis.org/dtd/mybatis-3-config.dtd">
    3. <configuration>
    4. <!-- 外部引入配置 -->
    5. <properties resource="db.properties"/>
    6. <!-- 类型别名,方便后面的UserMapper.xml中使用 -->
    7. <typeAliases>
    8. <!-- 这种可以自定义别名 -->
    9. <!--typeAlias alias="User" type="pojo.User"-->
    10. <!-- 扫描全包,别名为包下类名 -->
    11. <package name="pojo"/>
    12. </typeAliases>
    13. <environments default="development">
    14. <environment id="development">
    15. <transactionManager type="JDBC"/>
    16. <dataSource type="POOLED">
    17. <property name="driver" value="${driver}"/>
    18. <property name="url" value="${url}"/>
    19. <property name="username" value="${username}"/>
    20. <property name="password" value="${password}"/>
    21. </dataSource>
    22. </environment>
    23. </environments>
    24. <!-- 映射器 -->
    25. <mappers>
    26. <mapper resource="mapper/UserMapper.xml"/>
    27. <!--mapper class="mapper.UserMapper"-->
    28. <!--package name="mapper"-->
    29. </mappers>
    30. </configuration>
  2. 编写MyBatis工具类Util(MyBatis.util)

  1. public class MybatisUtil {
  2. // 提升这个变量的作用域
  3. private static SqlSessionFactory sqlSessionFactory;
  4. static {
  5. try {
  6. // 加载核心配置文件
  7. String resource = "mybatis-Config.xml";
  8. InputStream inputStream = Resources.getResourceAsStream(resource);
  9. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. // SqlSession实例的geter方法
  15. public static SqlSession getSqlSession(){
  16. return sqlSessionFactory.openSession();
  17. }
  18. }

1.3 junit测试

  • 增(需要提交事务)
  1. public class addUser {
  2. @Test
  3. public void addUser(){
  4. SqlSession sqlSession = MybatisUtil.getSqlSession();
  5. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  6. mapper.addUser(new User(3,"y","13245"));
  7. sqlSession.commit();
  8. sqlSession.close();
  9. }
  10. }
  • 删(需要提交事务)
  1. @Test
  2. public void delUserById(){
  3. SqlSession sqlSession = MybatisUtil.getSqlSession();
  4. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  5. mapper.delUserById(3);
  6. sqlSession.commit();
  7. sqlSession.close();
  8. }
  1. @Test
  2. public void findAll(){
  3. // 获取Session
  4. SqlSession session = MybatisUtil.getSqlSession();
  5. // 使用getMapper方式
  6. UserMapper mapper = session.getMapper(UserMapper.class);
  7. // 执行SQL语句
  8. List<User> userList = mapper.findAll();
  9. for (User user : userList) {
  10. System.out.println(user);
  11. }
  12. // 关闭Session
  13. session.close();
  14. }
  • 改(需要提交事务)
  1. @Test
  2. public void updateUser(){
  3. SqlSession sqlSession = MybatisUtil.getSqlSession();
  4. UserMapper mapper = sqlSession.getMapper(UserMapper.clas
  5. mapper.updateUser(new User(2, "x", "12344"));
  6. sqlSession.commit();
  7. sqlSession.close();
  8. }
  • 模糊查询(字符串用%%包围)

    1. @Test
    2. public void userList(){
    3. SqlSession sqlSession = MybatisUtil.getSqlSession();
    4. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    5. List<User> userList = mapper.getUserLike("%y%");
    6. for (User user : userList) {
    7. System.out.println(user);
    8. }
    9. sqlSession.close();
    10. }
  • 使用map参数(优点:使用map你需要什么参数就put什么参数,不需要像实体类那样new一个需要写出去全部属性)

    1. @Test
    2. public void addUser2(){
    3. SqlSession sqlSession = MybatisUtil.getSqlSession();
    4. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    5. Map<String, Object> map = new HashMap<>();
    6. map.put("userId",5);
    7. map.put("passWord","1234);
    8. mapper.addUser2(map);
    9. sqlSession.commit();
    10. sqlSession.close();
    11. }

    1.4 注意问题:

  • 每个操作使用不同的标签,比如插入语句使用insert标签

  • 在映射文件中使用parameterType属性指定参数数据类型,resultType属性指定返回类型
  • Sql语句中可以使用#{实体属性名}方式引用实体中的属性值
  • 插入、修改、删除操作涉及数据库数据变化,所以要使用sqlSession对象显示的提交事务,即sqlSession.commit()
  • 最后关闭,sqlSession.close()

2 、结果映射(ResultMap)