mybatis->mybatis自动连接数据库生成实体和dao和xml和Example

本文用的是maven,idea15

Mabatis三剑客分别是:mybatis-generator、mybatis-plugin、mybatis-pagehelper

一、mybatis-generator

根据我们的数据库自动生成pojo、dao和xml文件 
pojo里面放的是跟数据库字段一一对应的对象、dao层是接口,供service使用,xml是这个dao层接口的实现,sql语句都写在xml里

1.引入mabatis-generator

pom.xml里引入配置

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
          <encoding>UTF-8</encoding>
          <compilerArguments>
            <extdirs>${project.basedir}/src/main/webapp/WEB-INF/lib/</extdirs>
          </compilerArguments>
        </configuration>
</plugin>

引入generatorConfig.xml 
generatorConfig.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>
    <!--导入属性配置-->
    <properties resource="datasource.properties"></properties>

    <!--指定特定数据库的jdbc驱动jar包的位置-->
    <classPathEntry location="${db.driverLocation}"/>

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

        <!-- optional,旨在创建class时,对注释进行控制 -->
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接 -->
        <jdbcConnection
                driverClass="${db.driverClassName}"
                connectionURL="${db.url}"
                userId="${db.username}"
                password="${db.password}">
        </jdbcConnection>


        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            targetPackage     指定生成的model生成所在的包名
            targetProject     指定在该项目下所在的路径
        -->
        <!--<javaModelGenerator targetPackage="com.mmall.pojo" targetProject=".\src\main\java">-->
        <javaModelGenerator targetPackage="com.mmall.pojo" targetProject="./src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加 构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        <!--<sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">-->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        -->

        <!-- targetPackage:mapper接口dao生成的位置 -->
        <!--<javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject=".\src\main\java">-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject="./src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>


        <table tableName="mmall_shipping" domainObjectName="Shipping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_cart" domainObjectName="Cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_cart_item" domainObjectName="CartItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_order_item" domainObjectName="OrderItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_pay_info" domainObjectName="PayInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        <table tableName="mmall_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <columnOverride column="detail" jdbcType="VARCHAR" />
            <columnOverride column="sub_images" jdbcType="VARCHAR" />
        </table>
        <table tableName="mmall_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>


        <!-- mybatis插件的搭建 -->
    </context>
</generatorConfiguration>

2.新建datasource.properties文件,配置数据库连接信息(这里配置本地数据库)

这里写图片描述

db.driverLocation=F:/IdeaProjects/mmall/src/main/tool/mysql-connector-java-5.1.6-bin.jar
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mmall?useUnicode=true&amp;characterEncoding=UTF-8
db.username=root
db.password=940724

配置完之后,就点击idea的左下角有个小按钮,把右侧的maven project按钮调出来(右侧已有的请忽略) 
这里写图片描述 
点击maven project,并选定插件加载(双击就行) 
这里写图片描述 
下方的控制台,出现build success就是成功了,就会发现dao的包和pojo包会生成好了接口和数据对象实体类,以及生成一个mapper文件夹,里面存储着数据库里各个实体的xml文件

注意mapper里生成的文件夹,我在创建的时候把时间戳给加里了,如果要完美的用的话,需要把时间戳优化一下

把insert标签下的#{createTime,jdbcType=TIMESTAMP}和#{updateTime,jdbcType=TIMESTAMP}改成now()

把update标签下的#{updateTime,jdbcType=TIMESTAMP}改成now()

这个now()方法是数据库自带的函数,表示现在的时间


二、mybatis-plugin

我用的是idea15,如果其他版本不好用的,可以换成idea 15 
这是一个能够追踪dao接口和mapper文件里xml的一个插件

  • 提供Mapper接口与配置文件中对应SQL的导航

  • 提供Mapper接口与配置文件中对应SQL的导航

  • 编辑XML文件时自动补全

  • 根据Mapper接口, 使用快捷键生成xml文件及SQL标签

  • ResultMap中的property支持自动补全,支持级联(属性A.属性B.属性C)

  • 快捷键生成@Param注解

  • XML中编辑SQL时, 括号自动补全

  • XML中编辑SQL时, 支持参数自动补全(基于@Param注解识别参数)

  • 自动检查Mapper XML文件中ID冲突

  • 自动检查Mapper XML文件中错误的属性值

  • 支持Find Usage

  • 支持重构从命名

  • 支持别名

  • 自动生成ResultMap属性

  • 快捷键: Option + Enter(Mac) | Alt + Enter(Windows)

效果:点击dao可以追踪到xml,,同理点击xml的sql右边小箭头,可以追踪到dao方法

这里写图片描述

1、安装插件:

这里写图片描述
然后重启下idea

2.mybatis-plugin插件破解

到这个网址去 
https://github.com/myoss/profile/tree/master/idea/plugin/MybatisPlugin 
你看到了一个Git仓库,先clone下来,不会clone的down下来,记住路径 
接下来,你看到一堆版本,选择你安装的mybatis_plugin版本号,比如我的是IDEA15版本的,我安装版本就是v2.64,进入v2.64你会看到一个com文件夹,牢牢记住这个文件夹有大作用

这里写图片描述

点击如图所示的右上角的fork,登录自己的github,登录之后,会发现右边有个绿色的Dowload图标,点击那个就可以下载别人的项目了 
这里写图片描述

(1) windows破解

首先你要找到mybatis_plus.jar的位置,位置一般在这里 
C:\Users\youname(你自己的文档).IntelliJIdea\config\plugins\mybatis_plus\lib 
用winRAR打开 
这里写图片描述 
将下载好的破解,与plugin插件压缩包中的文件更换,拖入压缩包,更换就行 
这里写图片描述

重启你的IDEA,完毕,破解搞定

(2)mac破解

使用find命令在你的用户目录下查找mybatis_plus.jar这个文件

find ~ -name "mybatis_plus.jar"
  • 1

OK,拿到一个地址,然后进去

cd /Users/XXXXX/Library/Application Support/IntelliJIdea15/mybatis_plus/lib
  • 1

看到了2个文件

#创建一个文件夹
mkdir m
#进去 
cd m
#拷贝到m文件夹中 
cp ../mybatis_plus.jar .
#解压jar包
jar xf mybatis_plus.jar 
#复制com文件夹到这里   路径根据你情况而定,版本号也根据你情况而定
cp -r ~/Workspace/github/mybatis_plus/idea/plugin/MybatisPlugin/v2.7\~v2.83/com .
#重新打为jar包
jar cf mybatis_plus.jar *
#复制到m的上层目录
cp mybatis_plus.jar ../

重启你的IDEA,完毕,破解搞定


三、Mybatis-pageHelper

是一个开源的分页插件(如下网址有插件的全介绍) 
https://github.com/pagehelper/Mybatis-PageHelper 
它的原理,是通过spring的AOP来实现的,这个插件能在执行sql的时候,把相关的数据再执行一次

1.pom.xml里添加依赖

<dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.1.0</version>
    </dependency>

    <dependency>
      <groupId>com.github.miemiedev</groupId>
      <artifactId>mybatis-paginator</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>com.github.jsqlparser</groupId>
      <artifactId>jsqlparser</artifactId>
      <version>0.9.4</version>
    </dependency>

2.在spring配置文件里添加配置

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:mappers/*Mapper.xml"/>

        <!-- 分页插件 -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <value>
                            dialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>

    </bean>

注意不同数据库的方言的使用

这样三剑客就都配置OK了

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: mybatis-config.xml 模板如下: ```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> <settings> <!-- 设置全局属性 --> </settings> <typeAliases> <!-- 指定类型别名 --> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <!-- 数据库连接信息 --> </dataSource> </environment> </environments> <mappers> <!-- 指定映射器 --> </mappers> </configuration> ``` 其中,settings、typeAliases、environments、mappers 是 mybatis-config.xml 的四个重要元素。 - settings 中定义了全局属性,如开启驼峰命名规则等。 - typeAliases 中定义了类型别名,可以简化映射文件中类名的编写。 - environments 中定义了环境信息,包括事务管理器和数据源。 - mappers 中指定了映射文件的位置。 请注意,上面的模板是基本的配置,根据需要可能会有修改。 ### 回答2: mybatis-config.xmlMyBatis框架中的配置文件,用于配置和管理MyBatis的各个组件和功能。 这个模板文件包含了一些重要的配置项和属性,可以根据用户的需求进行自定义。以下是一个常见的mybatis-config.xml模板示例: ```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> <properties> <!-- 数据库连接配置 --> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo" /> <property name="username" value="root" /> <property name="password" value="123456" /> </properties> <typeAliases> <!-- 实体类别名配置 --> <package name="com.example.entity" /> </typeAliases> <mappers> <!-- Mapper接口配置 --> <mapper resource="com/example/dao/UserMapper.xml" /> </mappers> <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> </configuration> ``` 通过这个模板,我们可以配置数据库的连接信息、实体类别名、Mapper接口以及事务管理器和数据源等。 使用时,可根据实际情况修改数据库连接信息、实体类别名和Mapper接口的路径等。这样可以方便地进行数据库操作和管理,提供了灵活性和扩展性。 注意,在实际的项目中,mybatis-config.xml文件可能还会包含其他的配置项,以满足具体的需求。这只是一个简单的模板示例,具体的配置内容需要根据项目的需求进行调整。 ### 回答3: mybatis-config.xmlMyBatis框架的主配置文件,用于配置MyBatis的全局属性和插件。下面是一个简单的mybatis-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> <!-- 设置MyBatis的运行环境 --> <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://localhost:3306/testdb"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!-- 设置映射文件 --> <mappers> <mapper resource="com/example/mapper/ExampleMapper.xml"/> </mappers> </configuration> 在配置文件中,可以配置多个environments环境,根据实际情况选择对应的环境用于数据源和事务管理器的配置。在dataSource标签中,可以配置数据库的连接信息,包括驱动名、URL、用户名和密码等。在mappers标签中,可以配置映射文件的路径,其中每个映射文件对应一个Mapper接口。 通过这个模板,我们可以根据实际需要进行修改和扩展,例如更换数据库的连接信息、配置多数据源、添加插件等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值