zoukankan      html  css  js  c++  java
  • MyBatis---自动创建表

    该项目基于Maven实现

    该项目实现了在项目启动时,对数据库表进行操作

    源码下载

    实现步骤:

    1.向pom.xml文件添加maven依赖

    <dependency>
      <groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
      <artifactId>mybatis-enhance-actable</artifactId>
      <version>1.0.1</version>
    </dependency>

    2.在项目资源文件夹中创建autoCreateTable.properties(数据库表操作配置)文件

    #create:系统启动后,会将所有的表删除掉,然后根据entity类中配置的结构重新建表,该操作会破坏原有数据。
    #update:系统启动后,会根据entity类中配置的结构对表字段进行增删改操作
    #------
    增:添加数据库表;根据实体向数据库表中添加字段
    #------删:根据实体删除数据库表中的字段;不能实现删除项目实体类而删除数据库表
    #------改:修改数据库字段的名字、属性
    #none:系统不做任何处理 mybatis.table.auto=update #用来配置要扫描的用于创建表的对象的包名 mybatis.model.pack=com.sunchenbin.store.model
    #用来区别数据库,预计会支持这四种数据库mysql/oracle/sqlserver/postgresql,但目前仅支持mysql mybatis.database.type=mysql

    3.修改applicationContext.xml文件

    添加扫描底层注入代码

    <context:component-scan base-package="com.gitee.sunchenbin.mybatis.actable.manager.*" />

    引入数据库操作配置文件autoCreateTable.properties

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
      <property name="locations">
        <list>
          <value>classpath*:config/autoCreateTable.properties</value>
        </list>
      </property>
    </bean>
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
      <property name="properties" ref="configProperties" />
    </bean>

    添加mybatis.actable的mapper文件包,用于对数据库表进行操作。在正常项目中,已有该配置,即只需添加value值即可

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="mapperLocations">
        <array>
          <value>classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml</value>
        </array>
      </property>
    </bean>

    添加mybatis.actable的dao包。在正常项目中,已有该配置,即只需在value值的最后添加;com.gitee.sunchenbin.mybatis.actable.dao.*即可

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.gitee.sunchenbin.mybatis.actable.dao.*" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    特别注意:

    项目引入配置文件不能使用如下方式

    <beans profile="production">
      <context:property-placeholder ignore-unresolvable="true" file-encoding="utf-8"
      location="classpath:config.properties,classpath:jdbc.properties" />
    </beans>

    只能使用如下代码代替

    <context:property-placeholder location="classpath:config.properties,classpath*:config/jdbc.properties" />
  • 相关阅读:
    面向对象编程总结Python
    垃圾收集器与内存分配策略
    自定义异常、异常处理注意点
    关于线程【一】——线程创建、停止、interrupted()和isInterrupted()区别
    Java内存区域
    HotSpot虚拟机对象
    异常——try、catch、finally、throw、throws
    关于线程【二】——线程同步和异步
    fillder代理调试
    新鲜出炉的Asp.Net MVC电子书
  • 原文地址:https://www.cnblogs.com/xiaobaizhiqian/p/8206622.html
Copyright © 2011-2022 走看看