MyBatis视频学习笔记

来源:互联网 发布:程序员常用画图工具 编辑:程序博客网 时间:2024/06/11 12:02
MyBatis:
1.MyBatis可以使用简单的XML或注解用于配制原始映射,支持定制化SQL;
2.MyBatis要用到的jar包:mybatis-3.1.1.jar,mysql驱动包mysql-connector.java-5.1.7-bin.jar;
3.MyBatis包含了一个Resources的工具类,包含了一些使用的方法:
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
4.config.xml配置文件详情:
<?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">//development表示开发模式,work表示工作模式,且default="development"必须与id="development"保持一致
    <environment id="development">
      <transactionManager type="JDBC"/>//使用JDBC来管理事物,也可以设置为MANAGED,表示让容器来管理事物
      <dataSource type="POOLED">//连接池
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/xxxMapper.xml"/>//注册映射文件
  </mappers>
</configuration>
5.MyBatis实体类xxx.java,映射文件可以是xxxMapper.xml;
6.实体类映射文件:
<mapper namespace="取值的目的是区别不同的映射文件">
  <select id="标识符,方便后边调用" parameterType="参数类型" resultType="返回值类型">
    select * from users where id =#{id}//传参写法
  </select>
</mapper>
7.配置好之后,xxxMapper.xml要在myBatis.xml中注册;
8.导入DTD文件,实现代码提示步骤:
windows-->Preferences-->XML-->XML Catalog-->Catalog Entity-->导入DTD文件;
9.MyBatis查询时传递参数的方法:#{id};
10.在myBatisConfig.xml配置文件中通过<properties resource="db.properties"/>来加载配置文件;
11.配置实体类的别名,简化sql映射文件中的引用
<typeAliases>
  <typeAlias type="com.xxx.User" alias="_User">
  <package name="com.xxx">//package方法在使用时可以直接用User代表实体类了,因为这里已经映射过包了
</typeAliases>//该配置文件放在配置文件中,而不是映射文件中
12.myBatis打印日志文件:首先添加log4j-1.2.16.jar,其次俩种方式配置日志文件,log4j.xml和log4j.properties方式,放在src目录下;
13.MyBatis<select id="" parameterMap=""或者是parameterType=""//俩种方式表示参数类型 resultMap=""或者是resultType=""//同理,俩种方式表示返回值类型>
14.MyBatis解决查询字段与实体类不对应的俩种方式,其一为查询出的字段其别名,别名对应实体类中的同名属性,
其二是使用<resultMap>封装映射关系,
<resultMap type="Entity" id="xxx">
  <id property="主键属性" column="表中的主键"/>
 <result property="普通属性" column="普通字段"/>
</resultMap>//此处的xxx名称在<select resultMap="xxx">中使用;
15.String name = null,String newName = name+"abc",newName = "nullabc";
16.MyBatis映射文件中编写SQL语句时,添加判断,实现动态SQL:SELECT  * FROM xxx WHERE <if test="判断条件">判断成立时,添加的SQL</if>...

0 0
原创粉丝点击