当前位置:   article > 正文

MyBatis

MyBatis

MyBatis是一款优秀的持久层框架,用于简化JDBC开发

持久层

负责将数据到保存到数据库的那一层代码

JavaEE三层架构:表现层、业务层、持久层

框架:

框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型

在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

1,模板

 其中:

(1)logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <!--
  4. CONSOLE :表示当前的日志信息是可以输出到控制台的。
  5. -->
  6. <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
  7. <encoder>
  8. <pattern>【%level】 %blue(%d{HH:mm:ss.SSS}) %cyan(【%thread】) %boldGreen(%logger{15}) - %msg %n</pattern>
  9. </encoder>
  10. </appender>
  11. <logger name="com.itheima" level="DEBUG" additivity="false">
  12. <appender-ref ref="Console"/>
  13. </logger>
  14. <root level="DEBUG">
  15. <appender-ref ref="Console"/>
  16. </root>
  17. </configuration>

(2)mybatis-config.xml

  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="com.mysql.jdbc.Driver"/>
  11. <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
  12. <property name="username" value="root"/>
  13. <property name="password" value="111111"/>
  14. </dataSource>
  15. </environment>
  16. </environments>
  17. <mappers>
  18. <mapper resource="UserMapper.xml"/>
  19. </mappers>
  20. </configuration>

(3)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. <mapper namespace="test">
  6. <select id="selectAll" resultType="com.jaa.pojo.User">
  7. select * from tb_user;
  8. </select>
  9. </mapper>
  1. public class MyBatisDemo {
  2. public static void main(String[] args) throws IOException{
  3. String resource = "mybatis-config.xml";
  4. InputStream inputStream = Resources.getResourceAsStream(resource);
  5. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  6. SqlSession sqlSession=sqlSessionFactory.openSession();
  7. List<User> users=sqlSession.selectList("test.selectAll");
  8. System.out.println(users);
  9. sqlSession.close();
  10. }
  11. }

2,解决SQL映射文件的警告提示

产生原因:ldea和数据库没有建立连接,不识别表信息

解决方式:在ldea中配置MySQL数据库连接

3,Mapper代理开发

目的:

解决原生方式中的硬编码

简化后期执行SQL

  1. List<User> users = sqlSession.selectList("test.selectAll");
  2. //获取UserMapper接口的代理对象 UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
  3. List<User> users=userMapper.selectAll();
  1. <typeAliases>
  2. <package name="com.jaa.pojo"/>
  3. </typeAliases>
<select id="selectAll" resultType="user">

其中package name会简化resultType的代码,更加简洁

4,配置文件完成功能列表清单

要完成的功能列表清单:

1.查询

        查询所有数据

        查看详情

        条件查询

2.添加

3.修改

        修改全部字段

        修改动态字段

4.删除

        删除一个

        批量删除

MybatisX是一款基于IDEA的快速开发插件,为效率而生。

主要功能:

XML和接口方法相互跳转

根据接口方法生成statement

5,查询

(1)查询所有

1.编写接口方法: Mapper接口

参数:无

结果:List<Brand>

2.编写SQL语句:SQL映射文件

3.执行方法,测试

  1. @Test
  2. public void testSelectAll() throws IOException {
  3. //1.获取sqlSessionFactory
  4. String resource = "mybatis-config.xml";
  5. InputStream inputStream = Resources.getResourceAsStream(resource);
  6. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  7. //2.获取SqlSessionFactory对象
  8. SqlSession sqlSession = sqlSessionFactory.openSession();
  9. //3.获取Mapper的代理对象
  10. BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
  11. //4.执行方法
  12. List<Brand> brands=brandMapper.selectAll();
  13. System.out.println(brands);
  14. //5.释放资源
  15. sqlSession.close();
  16. }

实体类属性名和数据库表列名不一致,不能自动封装数据

1)起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样*可以定义<sql>片段,提升复用性

2) resultMap:定义<resultMap>完成不一致的属性名和列名的映射

id:主键字段的映射

result:一般字段的映射

  1. <resultMap id="brandResultMap" type="brand">
  2. <result column="brand_name" property="brandName"/>
  3. <result column="company_name" property="companyName"/>
  4. </resultMap>
  5. <select id="selectAll" resultMap="brandResultMap">
  6. select
  7. *
  8. from tb_brand;
  9. </select>

(2)查看详情

  1. <select id="selectById" resultMap="brandResultMap">
  2. select *
  3. from tb_brand where id=#{id};
  4. </select>

参数占位符:

1.#{}:会将其替换成?,为了防止sql注入问题

2.${}:拼sql,会存在sql注入问题

3.使用时机:

参数传递的时候:#{}

表格或者列名不固定的情况下:${}

特殊字符处理:

1.转义文字:<替代成&lt;

2.CDATA区:<替代成<![CDATA[     <    ]]>

(3)多条件查询

  1. //条件查询
  2. //散装参数
  3. //对象参数
  4. //map集合参数
  5. List<Brand> selectByCondition(@Param("status") int status,@Param("companyName")String companyName,@Param("brandName")String brandName);
  6. List<Brand> selectByCondition(Brand brand);
  7. List<Brand> selectByCondition(Map map);

 

  1. <select id="selectByCondition" resultMap="brandResultMap">
  2. select *
  3. from tb_brand
  4. where
  5. status=#{status}
  6. and company_name like #{companyName}
  7. and brand_name like #{brandName};
  8. </select>
  1. //接收参数
  2. int status=1;
  3. String companyName="华为";
  4. String brandName="华为";
  5. //处理参数
  6. companyName="%"+companyName+"%";
  7. brandName="%"+brandName+"%";
  8. // Brand brand=new Brand();
  9. // brand.setStatus(status);
  10. // brand.setCompanyName(companyName);
  11. // brand.setBrandName(brandName);
  12. Map map=new HashMap();
  13. map.put("status",status);
  14. map.put("companyName",companyName);
  15. map.put("brandName",brandName);
  16. //1.获取sqlSessionFactory
  17. String resource = "mybatis-config.xml";
  18. InputStream inputStream = Resources.getResourceAsStream(resource);
  19. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  20. //2.获取SqlSessionFactory对象
  21. SqlSession sqlSession = sqlSessionFactory.openSession();
  22. //3.获取Mapper的代理对象
  23. BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
  24. //4.执行方法
  25. // List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
  26. // List<Brand> brands=brandMapper.selectByCondition(brand);
  27. List<Brand> brands=brandMapper.selectByCondition(map);
  28. System.out.println(brands);
  29. //5.释放资源
  30. sqlSession.close();

(4)多条件-动态条件查询

动态条件查询!
if:条件判断
test:逻辑符表达式

问题:当companyName开始时,会带有and开头,使其报错
如:select * from tb_brand where and company_name like ?
带有and使语法错误

解决方法:
1.使用恒等式 如:1=1

2.myBatis提供的标签where

  1. <select id="selectByCondition" resultMap="brandResultMap">
  2. select *
  3. from tb_brand
  4. where 1=1
  5. <if test="status !=null">
  6. status=#{status}
  7. </if>
  8. <if test="companyName !=null and companyName!='' ">
  9. and company_name like #{companyName}
  10. </if>
  11. <if test="brandName !=null and brandName !='' ">
  12. and brand_name like #{brandName}
  13. </if>
  14. </select>
  15. <select id="selectByCondition" resultMap="brandResultMap">
  16. select *
  17. from tb_brand
  18. <where>
  19. <if test="status !=null">
  20. status=#{status}
  21. </if>
  22. <if test="companyName !=null and companyName!='' ">
  23. and company_name like #{companyName}
  24. </if>
  25. <if test="brandName !=null and brandName !='' ">
  26. and brand_name like #{brandName}
  27. </if>
  28. </where>
  29. </select>

(5)单条件-动态条件查询

当用户什么都不输入的时候,需要查询所有的

可以使用<otherwise>标签1=1来查询

或者

可以使用<where>来查询

  1. <select id="selectByConditionSingle" resultMap="brandResultMap">
  2. Select *
  3. from tb_brand
  4. where
  5. <choose>
  6. <when test="status != null">
  7. status=#{status}
  8. </when>
  9. <when test="companyName != null and companyName!=''">
  10. and company_name like #{companyName}
  11. </when>
  12. <when test="brandName != null and brandName !='' ">
  13. and brand_name like #{brandName}
  14. </when>
  15. <otherwise>
  16. 1=1
  17. </otherwise>
  18. </choose>
  19. </select>
  20. <select id="selectByConditionSingle" resultMap="brandResultMap">
  21. Select *
  22. from tb_brand
  23. <where>
  24. <choose>
  25. <when test="status != null">
  26. status=#{status}
  27. </when>
  28. <when test="companyName != null and companyName!=''">
  29. and company_name like #{companyName}
  30. </when>
  31. <when test="brandName != null and brandName !='' ">
  32. and brand_name like #{brandName}
  33. </when>
  34. </choose>
  35. </where>
  36. </select>

6,添加

运行正常时,不会自动提交事务,需自己手动提交

sqlSession.commit();

但是可以自动开启提交事务

如只需在openSession()中的()中添加open

SqlSession sqlSession = sqlSessionFactory.openSession(open);
  1. //4.执行方法
  2. brandMapper.add(brand);
  3. //提交事务
  4. sqlSession.commit();

主键返回:

  1. <insert id="add" useGeneratedKeys="true" keyProperty="id">
  2. insert into tb_brand (brand_name,company_name,ordered,description,status)
  3. values(#{brandName},#{companyName},#{ordered},#{description},#{status});
  4. </insert>

7,修改

(1)修改全部字段

  1. <update id="update">
  2. update tb_brand
  3. set
  4. brand_name=#{brandName},
  5. company_name=#{companyName},
  6. ordered=#{ordered},
  7. description=#{description},
  8. status=#{status}
  9. where id=#{id};
  10. </update>

(2)修改动态字段

其中<set>保证了语法不会出错的问题

  1. <update id="update">
  2. update tb_brand
  3. <set>
  4. <if test="brandName != null and brandName !='' ">
  5. brand_name=#{brandName},
  6. </if>
  7. <if test="companyName != null and companyName !='' ">
  8. company_name=#{companyName},
  9. </if>
  10. <if test="ordered != null ">
  11. ordered=#{ordered},
  12. </if>
  13. <if test="description != null and description !='' ">
  14. description=#{description},
  15. </if>
  16. <if test="status != null ">
  17. status=#{status}
  18. </if>
  19. </set>
  20. where id=#{id};
  21. </update>

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号