Mybatis关系映射及Mybatis逆向工程

本文详细介绍了MyBatis框架的高级特性,包括主键映射、SQL元素复用、级联映射及逆向工程自动生成代码的方法。通过实际代码示例,深入解析了这些特性如何提高开发效率并简化复杂操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Mybatis主键映射

useGeneratedKeys 默认值为false。设置为true表示将自增时产生的主键值赋值给keyProperty指定的属性,其为传入实例User的属性,在执行插入语句后,Mybatis会自动调用User的setId() 将数据库主键值赋给当前实例的id属性,我们只需调用getId()获取即可

<!--   useGeneratedKeys 为true可将主键自动设置给keyProperty指定系统-->
    <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into user value (#{id},#{name},#{age},#{phone},#{info})
    </insert>

2.sql元素与include元素

<!--    sql标签:定义可重复使用sql段,include标签:引用sql标签-->
    <sql id="diyColumn">
        id,name,age,info
    </sql>
    <select id="getAll" resultType="User">
        select <include refid="diyColumn" /> from user
    </select>

sql元素可以用于定义一条Sql的一部分,方便后面的Sql引用它。比如最典型的列名,通常情况下要在select、insert等语句中反复去编写他们,特别是那些字段较多的表更是如此,在Mybatis中,只需要在sql元素中对其编写一次便能够在其他元素中通过include引用它了。

3.Mybatis级联映射

toMany:一对多(多对多)

<!--    一对多,多对多-->
    <select id="testOneToMany" parameterType="int" resultMap="teacherMap" >
        select * from student s,teacher t where s.tid=t.tid and t.tid=#{tid}
    </select>

    <resultMap id="teacherMap" type="Teacher">
        <id property="tid" column="tid" />
        <result property="tname" column="tname" />
        <result property="tclass" column="tclass" />
        <collection property="sList" ofType="Student">
            <id property="sid" column="sid" />
            <result property="sname" column="sname" />
            <result property="score" column="score" />
            <result property="tid" column="tid" />
        </collection>
    </resultMap>

toOne:多对一(一对一)

<!--多对一,一对一-->
    <select id="testManyToOne" resultMap="studentMap">
       select * from student s,teacher t where s.tid=t.tid
    </select>
        <resultMap id="studentMap" type="Student">
            <id property="sid" column="sid"/>
            <result property="sname" column="sname"/>
            <result property="score" column="score"/>
            <result property="tid" column="tid" />
 <!--一对一,多对一-->
            <association property="teacher" javaType="Teacher">
                <id property="tid" column="tid" />
                <result property="tname" column="tname"/>
                <result property="tclass" column="tclass" />
            </association>
        </resultMap>

另外一种写法:

<!--多对一,一对一-->
    <select id="testManyToOne" resultMap="studentMap">
       select * from student s,teacher t where s.tid=t.tid
    </select>
        <resultMap id="studentMap" type="Student">
            <id property="sid" column="sid"/>
            <result property="sname" column="sname"/>
            <result property="score" column="score"/>
            <result property="tid" column="tid" />
            <association property="teacher" resultMap="t_map"/>
        </resultMap>
    <resultMap id="t_map" type="Teacher">
        <id property="tid" column="tid"/>
        <result property="tname" column="tname" />
        <result property="tclass" column="tclass" />
    </resultMap>

4.Mybatis 逆向工程(自动生成代码)

pom.xml

<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.6</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.6</version>
            <configuration>
                <verbose>true</verbose><!--允许移动生成的文件 -->
                <overwrite>true</overwrite> <!--允许覆盖生成的文件 -->
            </configuration>
        </plugin>
    </plugins>
</build>

mbg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

   <context id="ReverseTest" targetRuntime="MyBatis3">

      <!-- 配置生成的实体类的注释问题,设置为true不生成 ,如果不设置的话会默认生成很多的注释 -->
      <commentGenerator>
         <property name="suppressAllComments" value="true" />
      </commentGenerator>

      <!-- 配置连接数据库,注意下面的driverClass,不同版本的数据库驱动不同的 -->
      <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                  connectionURL="jdbc:mysql://localhost:3306/web_db"
                  userId="root"
                  password="123456">
      </jdbcConnection>

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

      <!-- 指定javabean的生成位置 -->
      <javaModelGenerator targetPackage="cn.goktech.entity"
         targetProject=".\src\main\java">
         <property name="enableSubPackages" value="true" />
         <property name="trimStrings" value="true" />
      </javaModelGenerator>

      <!-- 指定sql映射文件的生成位置 -->
      <sqlMapGenerator targetPackage="mapper"
         targetProject=".\src\main\resources">
         <property name="enableSubPackages" value="true" />
      </sqlMapGenerator>


      <!-- 指定dao接口生成的位置,mapper接口,targetPackage是预生成的包,targetProject是目录 -->
      <javaClientGenerator type="XMLMAPPER"
         targetPackage="cn.goktech.dao" targetProject=".\src\main\java">
         <property name="enableSubPackages" value="true" />
      </javaClientGenerator>


      <!-- table指定每个表的生成策略 ,后面的domainObjectName是前面的tableName表要生成的javaBean的名字 -->
      <table tableName="user" domainObjectName="User">
      </table>
      <table tableName="teacher" domainObjectName="Teacher">
      </table>
      <table tableName="student" domainObjectName="Student">
      </table>

   </context>
</generatorConfiguration>

MBGTest

public class MBGTest {

    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("src/main/resources/mbg.xml");     //你的mybatis generator 配置文件名
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        System.out.println("生成结束");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值