赞
踩
MyBatis是一款优秀的持久层框架,用于简化JDBC开发
持久层:
负责将数据到保存到数据库的那一层代码
JavaEE三层架构:表现层、业务层、持久层
框架:
框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型
在框架的基础之上构建软件编写更加高效、规范、通用、可扩展
其中:
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration>
- <!--
- CONSOLE :表示当前的日志信息是可以输出到控制台的。
- -->
- <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>【%level】 %blue(%d{HH:mm:ss.SSS}) %cyan(【%thread】) %boldGreen(%logger{15}) - %msg %n</pattern>
- </encoder>
- </appender>
-
- <logger name="com.itheima" level="DEBUG" additivity="false">
- <appender-ref ref="Console"/>
- </logger>
-
- <root level="DEBUG">
- <appender-ref ref="Console"/>
- </root>
- </configuration>
- <?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>
- <environments default="development">
- <environment id="development">
- <transactionManager type="JDBC"/>
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
- <property name="username" value="root"/>
- <property name="password" value="111111"/>
- </dataSource>
- </environment>
- </environments>
- <mappers>
- <mapper resource="UserMapper.xml"/>
- </mappers>
- </configuration>
- <?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="test">
- <select id="selectAll" resultType="com.jaa.pojo.User">
- select * from tb_user;
- </select>
- </mapper>
- public class MyBatisDemo {
- public static void main(String[] args) throws IOException{
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
- SqlSession sqlSession=sqlSessionFactory.openSession();
-
-
- List<User> users=sqlSession.selectList("test.selectAll");
-
- System.out.println(users);
-
- sqlSession.close();
- }
- }
产生原因:ldea和数据库没有建立连接,不识别表信息
解决方式:在ldea中配置MySQL数据库连接
目的:
解决原生方式中的硬编码
简化后期执行SQL
- List<User> users = sqlSession.selectList("test.selectAll");
-
- //获取UserMapper接口的代理对象 UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
- List<User> users=userMapper.selectAll();
- <typeAliases>
- <package name="com.jaa.pojo"/>
- </typeAliases>
<select id="selectAll" resultType="user">
其中package name会简化resultType的代码,更加简洁
要完成的功能列表清单:
1.查询
查询所有数据
查看详情
条件查询
2.添加
3.修改
修改全部字段
修改动态字段
4.删除
删除一个
批量删除
MybatisX是一款基于IDEA的快速开发插件,为效率而生。
主要功能:
XML和接口方法相互跳转
根据接口方法生成statement
1.编写接口方法: Mapper接口
参数:无
结果:List<Brand>
2.编写SQL语句:SQL映射文件
3.执行方法,测试
- @Test
- public void testSelectAll() throws IOException {
- //1.获取sqlSessionFactory
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
- //2.获取SqlSessionFactory对象
- SqlSession sqlSession = sqlSessionFactory.openSession();
-
- //3.获取Mapper的代理对象
- BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
-
- //4.执行方法
- List<Brand> brands=brandMapper.selectAll();
- System.out.println(brands);
-
- //5.释放资源
- sqlSession.close();
- }
实体类属性名和数据库表列名不一致,不能自动封装数据
1)起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样*可以定义<sql>片段,提升复用性
2) resultMap:定义<resultMap>完成不一致的属性名和列名的映射
id:主键字段的映射
result:一般字段的映射
- <resultMap id="brandResultMap" type="brand">
- <result column="brand_name" property="brandName"/>
- <result column="company_name" property="companyName"/>
- </resultMap>
-
-
- <select id="selectAll" resultMap="brandResultMap">
- select
- *
- from tb_brand;
-
- </select>
- <select id="selectById" resultMap="brandResultMap">
- select *
- from tb_brand where id=#{id};
- </select>
参数占位符:
1.#{}:会将其替换成?,为了防止sql注入问题
2.${}:拼sql,会存在sql注入问题
3.使用时机:
参数传递的时候:#{}
表格或者列名不固定的情况下:${}
特殊字符处理:
1.转义文字:<替代成<
2.CDATA区:<替代成<![CDATA[ < ]]>
- //条件查询
- //散装参数
- //对象参数
- //map集合参数
-
- List<Brand> selectByCondition(@Param("status") int status,@Param("companyName")String companyName,@Param("brandName")String brandName);
- List<Brand> selectByCondition(Brand brand);
- List<Brand> selectByCondition(Map map);
- <select id="selectByCondition" resultMap="brandResultMap">
- select *
- from tb_brand
- where
- status=#{status}
- and company_name like #{companyName}
- and brand_name like #{brandName};
- </select>
- //接收参数
- int status=1;
- String companyName="华为";
- String brandName="华为";
-
- //处理参数
- companyName="%"+companyName+"%";
- brandName="%"+brandName+"%";
-
- // Brand brand=new Brand();
- // brand.setStatus(status);
- // brand.setCompanyName(companyName);
- // brand.setBrandName(brandName);
- Map map=new HashMap();
- map.put("status",status);
- map.put("companyName",companyName);
- map.put("brandName",brandName);
-
- //1.获取sqlSessionFactory
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
- //2.获取SqlSessionFactory对象
- SqlSession sqlSession = sqlSessionFactory.openSession();
-
- //3.获取Mapper的代理对象
- BrandMapper brandMapper=sqlSession.getMapper(BrandMapper.class);
-
- //4.执行方法
- // List<Brand> brands = brandMapper.selectByCondition(status, companyName, brandName);
- // List<Brand> brands=brandMapper.selectByCondition(brand);
- List<Brand> brands=brandMapper.selectByCondition(map);
- System.out.println(brands);
-
- //5.释放资源
- sqlSession.close();
动态条件查询!
if:条件判断
test:逻辑符表达式
问题:当companyName开始时,会带有and开头,使其报错
如:select * from tb_brand where and company_name like ?
带有and使语法错误
解决方法:
1.使用恒等式 如:1=1
2.myBatis提供的标签where
- <select id="selectByCondition" resultMap="brandResultMap">
- select *
- from tb_brand
- where 1=1
- <if test="status !=null">
- status=#{status}
- </if>
- <if test="companyName !=null and companyName!='' ">
- and company_name like #{companyName}
- </if>
- <if test="brandName !=null and brandName !='' ">
- and brand_name like #{brandName}
- </if>
-
- </select>
-
- <select id="selectByCondition" resultMap="brandResultMap">
- select *
- from tb_brand
- <where>
- <if test="status !=null">
- status=#{status}
- </if>
- <if test="companyName !=null and companyName!='' ">
- and company_name like #{companyName}
- </if>
- <if test="brandName !=null and brandName !='' ">
- and brand_name like #{brandName}
- </if>
- </where>
- </select>
当用户什么都不输入的时候,需要查询所有的
可以使用<otherwise>标签1=1来查询
或者
可以使用<where>来查询
- <select id="selectByConditionSingle" resultMap="brandResultMap">
- Select *
- from tb_brand
- where
- <choose>
- <when test="status != null">
- status=#{status}
- </when>
- <when test="companyName != null and companyName!=''">
- and company_name like #{companyName}
- </when>
- <when test="brandName != null and brandName !='' ">
- and brand_name like #{brandName}
- </when>
- <otherwise>
- 1=1
- </otherwise>
- </choose>
-
- </select>
-
-
- <select id="selectByConditionSingle" resultMap="brandResultMap">
- Select *
- from tb_brand
- <where>
- <choose>
- <when test="status != null">
- status=#{status}
- </when>
- <when test="companyName != null and companyName!=''">
- and company_name like #{companyName}
- </when>
- <when test="brandName != null and brandName !='' ">
- and brand_name like #{brandName}
- </when>
-
- </choose>
- </where>
- </select>
运行正常时,不会自动提交事务,需自己手动提交
sqlSession.commit();
但是可以自动开启提交事务
如只需在openSession()中的()中添加open
SqlSession sqlSession = sqlSessionFactory.openSession(open);
-
- //4.执行方法
- brandMapper.add(brand);
-
- //提交事务
- sqlSession.commit();
主键返回:
- <insert id="add" useGeneratedKeys="true" keyProperty="id">
- insert into tb_brand (brand_name,company_name,ordered,description,status)
- values(#{brandName},#{companyName},#{ordered},#{description},#{status});
- </insert>
- <update id="update">
- update tb_brand
- set
- brand_name=#{brandName},
- company_name=#{companyName},
- ordered=#{ordered},
- description=#{description},
- status=#{status}
- where id=#{id};
- </update>
其中<set>保证了语法不会出错的问题
- <update id="update">
- update tb_brand
- <set>
- <if test="brandName != null and brandName !='' ">
- brand_name=#{brandName},
- </if>
- <if test="companyName != null and companyName !='' ">
- company_name=#{companyName},
- </if>
- <if test="ordered != null ">
- ordered=#{ordered},
- </if>
- <if test="description != null and description !='' ">
- description=#{description},
- </if>
- <if test="status != null ">
- status=#{status}
- </if>
- </set>
- where id=#{id};
- </update>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。