mybatis简单教程笔记 基本配置 动态sql Generator插件

Mybatis

概述

什么是MyBatis

  • 一款优秀的持久层框架
  • 支持定制化sql,存储过程一级高级映射
  • 避免了几乎所有jdbc代码和手动设置参数以及获取结果集
  • 可以使用简单的xml或注解来配置和映射原生类型,接口和java的pojo为数据库中的记录
  • 本是apache的开源项目ibatis 2010年迁移到了google code 改名为mybatis
  • 2013年迁移到github

持久化

  • 持久化是将程序数据在持久状态和瞬时状态间转换的机制。通俗的讲,就是瞬时数据(比如内存中的数据,是不能永久保存的)持久化为持久数据(比如持久化至数据库中,能够长久保存)。

优点

  • 简单易学
  • 灵活
  • sql和代码的分离,提高了可维护性
  • 提供映射标签,支持兑现与数据库的orm字段关系映射
  • 提供对象关系映射标签,支持兑现关系组建维护
  • 提供xml标签,支持编写动态sql

Config

依赖

<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>3.5.6version>
dependency>
环境配置

<environments default="development">
    <environment id="development">
        
        <transactionManager type="JDBC"/>
        <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>
引入外部配置文件
<properties resource="db.properties"/>
别名

方便mapper.xml中使用

还可以使用注解@Alias("")

<typeAliases>
    <typeAlias type="cn.lazy.pojo.User" alias="User"/>
    <package name="cn.lazy.pojo"/>
typeAliases>
映射

将接口与mapper.xml联系起来

<mappers>
	<mapper resource=""/>
    <mapper url=""/>
    <mapper class=""/>
    <package name=""/>
mappers>
日志

log4j.properties文件spring会自动加载

<settings>
    
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    
    
settings>

log4j.properties

#将等级为DEBUG日志信息输出到console和file这两个目的地,console和file的定义在下面
log4j.rootLogger=debug,console,file
#console输出相关设置
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= [%c]-%m%n

#文件输出的相关设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/lazy.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

Mapper

增删改查

最基本的例子

<select id="getUserById" parameterType="int" resultType="User">
    select *
    from user
    where id = #{id}
select>


<insert id="add" parameterType="User">
    insert into user
    values (#{id}, #{name}, #{password})
insert>

<update id="updateById" parameterType="User">
    update user
    set name=#{name},
    password=#{password}
    where id = #{id}
update>

<delete id="deleteById" parameterType="int">
    delete
    from user
    where id = #{id}
delete>
结果集映射

<resultMap id="userMap" type="User">
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="password" property="pwd"/>
resultMap>


<select id="getUserList" resultMap="userMap">
    select *
    from user
select>
一对多
<select id="getTeacher" resultMap="map">
	select s.id sid, s.name sname, t.id tid, t.name tname
    from student s,
         teacher t
    where s.tid = t.id and t.id = 1;
select>

<resultMap id="map" type="Teacher">
	<result property="id" column="tid"/>
    <result property="name" column="tn"/>
    <collection property="student" ofType="Student">
    	<result property="id" column="sid"/>
        <result property="name" column="sn"/>
    collection>
resultMap>
多对一

方法一

<select id="getStudent" resultMap="map">
select * from student
select>

<resultMap id="map" type="Student">
	<result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
resultMap>

<select id="getTeacher" resultType="Teacher">
	select * from teacher
select>

方法二 推荐使用

<select id="getStudent" resultMap="map">
	select s.id sid,s.name sn ,t.id tid ,t.name tn 
    from student s,teacher t 
    where s.tid = t.id
select>

<resultMap id="map" type="Student">
	<result property="id" column="sid"/>
    <result property="name" column="sn"/>
    <association property="teacher" javaType="Teacher">
    	<result property="id" column="tid"/>
        <result property="name" column="tn"/>
    association>
resultMap>
动态sql语句
<if test="">if>

<choose>
	<when test="">when>
    <otherwise>otherwise>
choose>


<where>where>


<trim prefix="WHERE" prefixOverrides="AND |OR ">
	<if test="id!=null">AND t.id=#{id}if>
    <if test="name!=null">OR t.name=#{name}if>
trim>
<trim prefix="set" suffixOverrides=",">
	<if test="id!=null">t.id=#{id},if>
trim>


<sql id="sql1">sql>
<include refid="sql1">include>
注解
//别名 写在类上面
@Alias("")
//sql语句 代替mapper.xml 建议简单sql使用注解
@Select("") 
@Insert("")
@Delete("")
@Update("")
//写在方法的每一个参数前 用于向sql语句对应传值.
@Param("")

插件

Generator

概述

MyBatis Generator,简称MBG

它只需要很少量的简单配置,就可以完成大量的表到Java对象的生成工作,拥有零出错和速度快的优点

生成
  • Model实体文件,一个数据库表对应生成一个 Model 实体;
  • Mapper 接口文件,数据数操作方法都在此接口中定义;
  • Mapper XML配置文件
依赖
<dependency>
    <groupId>org.mybatis.generatorgroupId>
    <artifactId>mybatis-generator-coreartifactId>
    <version>1.3.6version>
dependency>


<plugins>
    <plugin>
        <groupId>org.mybatis.generatorgroupId>
        <artifactId>mybatis-generator-maven-pluginartifactId>
        <version>1.4.0version>
        <configuration>
            <verbose>trueverbose>
            <overwrite>trueoverwrite>
        configuration>
        <executions>
            <execution>
                <id>Generate MyBatis Artifactsid>
                <goals>
                    <goal>generategoal>
                goals>
            execution>
        executions>
        <dependencies>
            <dependency>
                <groupId>org.mybatis.generatorgroupId>
                <artifactId>mybatis-generator-coreartifactId>
                <version>1.4.0version>
            dependency>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.23version>
            dependency>
        dependencies>
    plugin>
plugins>
配置

generatorConfig.xml



<generatorConfiguration>

    <properties resource="db.properties"/>
    
    

    <context id="simple" targetRuntime="MyBatis3Simple">

        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        commentGenerator>

        
        <jdbcConnection driverClass="${db.driver}"
                        connectionURL="${db.url}"
                        userId="${db.username}"
                        password="${db.password}">
            <property name="nullCatalogMeansCurrent" value="true"/>
        jdbcConnection>

        
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        
        <javaModelGenerator 
                targetPackage="com.lazy.lazyshop.pojo" 
                targetProject="src/main/java">
            <property name="enableSubPackage" value="true"/>
            <property name="trimStrings" value="true"/>
        javaModelGenerator>

        
        <sqlMapGenerator 
                targetPackage="com.lazy.lazyshop.dao"
                targetProject="src/main/java">
            <property name="enableSubPackage" value="true"/>
        sqlMapGenerator>

        
        <javaClientGenerator
                targetPackage="com.lazy.lazyshop.dao"
                targetProject="src/main/java"
                type="XMLMAPPER">
            <property name="enableSubPackage" value="true"/>
        javaClientGenerator>
        
        
        <table tableName="%"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="Mysql"/>
            
            
            <domainObjectRenamingRule searchString="^Lazy" replaceString=""/>
        table>
    context>
generatorConfiguration>
问题
  1. 插件不显示

    放在了里面 应同级

  2. Cannot instantiate object of type null

    Dao生成配置少写 type="XMLMAPPER"

你可能感兴趣的:(笔记,java,mybatis,mysql,spring)