該項目基於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" />