教程和代碼可以直接看github上的最新版,https://github.com/zyf970617/mybatis-auto-create-table ,
下面的信息是舊版的哦,代碼有一些是不能用的~
Mybatis
和Hibernate
是兩個比較熱門的持久層框架。使用起來也各有利弊(個人使用了幾個月的Hibernate
后還是決定回到Mybatis
的懷抱)
Mybatis
用了快兩年了,在我手上的發展史大概是這樣的
第一個階段
利用Mybatis-Generator
自動生成實體類
、DAO接口
和Mapping映射文件
。那時候覺得這個特別好用,大概的過程是這樣的
- 在數據庫中先建好表
- 配置好幾個
xml
文件(一般都是復制粘貼上一個項目的),然后根據數據庫中的表,生成實體類
、DAO接口
和Mapping映射文件
- 當需要添加數據操作的時候,先在
xml
中寫好CRUD
語句,然后在DAO接口層
寫接口,最后到映射文件
漸漸地,我忽然發現,這種方式越來越煩。改一個字段,要修改很多的配置文件,正常的修改一些查詢操作,也需要修改很多已有的配置。
第二個階段
在學長指導之下,走向了無xml
的Mybatis
之路。在這個階段,數據操作的過程大概是這樣的
- 設計需要的實體層
- 根據實體層,在數據庫中建表(非自動建表)
- 當需要進行增刪改查的時候,只需要在
Mapper
映射文件中,用對應的注解@Select
、@Delete
等進行相應的操作即可
相比于第一個階段的使用,在這個階段脫離了xml
的束縛,使用了全注解的形式。但是還是有很多的問題。比如,沒有自動生成的代碼,所有基礎的增刪改查都要自己寫。如果一個POJO
的屬性有20個,那你的insert
怕是有點長了。
第三個階段
這個階段是上一個階段的擴展,實現了一個通用的mapper
,所有的mapper
映射都繼承這個通用的mapper
,就只需要寫一些復雜的增刪改查就行了
然后就是這篇文章要寫的,不需要自己創建數據表,可以根據實體層,自動創建數據表,也就是省去了第二個階段中的第2步。
這是一個我很喜歡的功能,奈何只在Hibernate
中才有。不過在網上搜到一位大佬寫的博文,可以實現mybatis
自動創建數據表(目前僅限mysql
)
該博文涉及的所有代碼均已經開源,有特殊修改的可以自己修改相關代碼,然后重新打包即可
但是由于這個博文中的內容是基于
SpringMvc
的,所以附上一份自己修改后的基于SpringBoot
的簡單Demo(如果項目使用的是SpringMVC
,建議去看此框架開發者寫的博文)
SpringMvc版本:A.CTable開源框架Mybatis增強自動創建表/更新表結構/實現類似hibernate共通的增刪改查
SpringBoot整合A.CTable
- 項目目錄
- com
- config
- MyBatisMapperScannerConfig.java
- TestConfig.java
- entity
- Test.java
- mapper
- TestMapper.java
- DemoApplication.java
- 依賴包
<dependency>
<groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
<artifactId>mybatis-enhance-actable</artifactId>
<version>1.0.3</version>
</dependency>
-
application.properties
屬性配置文件
mybatis.table.auto=update
mybatis.model.pack=com.example.entity
mybatis.database.type=mysql
當mybatis.table.auto=create
時,系統啟動后,會將所有的表刪除掉,然后根據model中配置的結構重新建表,該操作會破壞原有數據。
當mybatis.table.auto=update
時,系統會自動判斷哪些表是新建的,哪些字段要修改類型等,哪些字段要刪除,哪些字段要新增,該操作不會破壞原有數據。
當mybatis.table.auto=none
時,系統不做任何處理。
mybatis.model.pack
這個配置是用來配置要掃描的用于創建表的對象的包名
- Spring配置文件
@Configuration
@ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"})
public class TestConfig {
@Value("${spring.datasource.driver-class-name}")
private String driver;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Bean
public PropertiesFactoryBean configProperties() throws Exception{
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
propertiesFactoryBean.setLocations(resolver.getResources("classpath*:application.properties"));
return propertiesFactoryBean;
}
@Bean
public DruidDataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(30);
dataSource.setInitialSize(10);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(true);
return dataSource;
}
@Bean
public DataSourceTransactionManager dataSourceTransactionManager() {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource());
return dataSourceTransactionManager;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.example.entity.*");
return sqlSessionFactoryBean;
}
}
@Configuration
@AutoConfigureAfter(TestConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.example.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
注意
MyBatisMapperScannerConfig
和TestConfig
不能合并,不然會出現@Value
為空的錯誤
- 實體層
@Table(name = "test")
public class Test extends BaseModel{
private static final long serialVersionUID = 5199200306752426433L;
@Column(name = "id",type = MySqlTypeConstant.INT,length = 11,isKey = true,isAutoIncrement = true)
private Integer id;
@Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 111)
private String name;
@Column(name = "description",type = MySqlTypeConstant.TEXT)
private String description;
@Column(name = "create_time",type = MySqlTypeConstant.DATETIME)
private Date create_time;
@Column(name = "update_time",type = MySqlTypeConstant.DATETIME)
private Date update_time;
@Column(name = "number",type = MySqlTypeConstant.BIGINT,length = 5)
private Long number;
@Column(name = "lifecycle",type = MySqlTypeConstant.CHAR,length = 1)
private String lifecycle;
@Column(name = "dekes",type = MySqlTypeConstant.DOUBLE,length = 5,decimalLength = 2)
private Double dekes;
//省略Setter、Getter
}
屬性上的注解定義了創建表時的各個字段的屬性
在配置文件中的,com.example.entity.*
需要換成自己項目中的實體層目錄,com.example.mapper.*
需要換成自己項目中的mapper
目錄
Github源碼地址:
https://github.com/zyf970617/mybatis-auto-create-table
要是對你有用就點個贊把~