Mybatis自动创建表,修改表字段

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" />

转自:https://www.cnblogs.com/xiaobaizhiqian/p/8206622.html

猜你喜欢

转载自blog.csdn.net/qq_42363892/article/details/86505515