1. 程式人生 > >SpringBoot+Mybatis 自動建立資料表

SpringBoot+Mybatis 自動建立資料表

MybatisHibernate是兩個比較熱門的持久層框架。使用起來也各有利弊(個人使用了幾個月的Hibernate後還是決定回到Mybatis的懷抱)


Mybatis用了快兩年了,在我手上的發展史大概是這樣的
第一個階段

利用Mybatis-Generator自動生成實體類DAO介面Mapping對映檔案。那時候覺得這個特別好用,大概的過程是這樣的

  1. 在資料庫中先建好表
  2. 配置好幾個xml檔案(一般都是複製貼上上一個專案的),然後根據資料庫中的表,生成實體類DAO介面Mapping對映檔案
  3. 當需要新增資料操作的時候,先在xml中寫好CRUD語句,然後在DAO介面層寫介面,最後到對映檔案

漸漸地,我忽然發現,這種方式越來越煩。改一個欄位,要修改很多的配置檔案,正常的修改一些查詢操作,也需要依次修改三個檔案。

第二個階段

在學長指導之下,走向了無xmlMybatis之路。在這個階段,資料操作的過程大概是這樣的

  1. 新建需要的實體層
  2. 根據實體層,在資料庫中建表(非自動建表)
  3. 當需要進行增刪改查的時候,只需要在Mapper對映檔案中,用對應的註解@Select@Delete等進行相應的操作即可

相比於第一個階段的使用,在這個階段脫離了xml的束縛,修改資料操作也只需要更改mapper層的資料即可。但是還是有很多的問題。比如,沒有自動生成的程式碼,所有基礎的增刪改查都要自己寫。如果一個POJO的屬性有20個,那你的insert怕是有點長了。

第三個階段

這個階段是上一個階段的擴充套件,用泛型實現了一個通用的mapper,所有的mapper

對映都繼承這個通用的mapper,基礎的增刪改查就不需要自己寫了。

再有就是這篇文章要寫的,不需要自己建立資料表,可以根據實體層,自動建立資料表,也就是省去了第二個階段中的第2步。

這是一個我很喜歡的功能,奈何只在Hibernate中才有。不過在網上搜到一位大佬寫的框架,可以實現mybatis自動建立資料表(目前僅限mysql

但是由於這個博文中的內容是基於SpringMvc的,所以附上一份自己修改後的基於SpringBoot的簡單Demo(如果專案使用的是SpringMVC,建議去看此框架開發者寫的博文)

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;
    }

}

注意MyBatisMapperScannerConfigTestConfig不能合併,不然會出現@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目錄

要是對你有用就點個贊把~

相關推薦

SpringBoot+Mybatis 自動建立資料

Mybatis和Hibernate是兩個比較熱門的持久層框架。使用起來也各有利弊(個人使用了幾個月的Hibernate後還是決定回到Mybatis的懷抱)Mybatis用了快兩年了,在我手上的發展史大概是這樣的第一個階段利用Mybatis-Generator自動生成實體類、DAO介面和Mapping對映檔案。

A.CTable 自動建立資料

1.新增依賴 <!-- A.CTable 自動建立資料表 --> <dependency> <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> <artifactId>my

springBoot下java自動建立資料庫

####SpringBoot環境啟動專案建立資料庫表 ####使用環境 windows+eclipse+mysql+navicat ####步驟 1.建立SpringBoot專案 2.新建資料庫,配置連線資訊 3.編寫初始化資料庫表類 4.執行檢視結果 1.建立

傳入Java物件 自動建立動態 並錄入資料

看到Hibernate你給一個物件,他就能動態的建立配置檔案裡面指定的表名,然後把資料錄入到資料庫,當初感覺是很神奇,不過,好像Hibernate不能動態的分表建立表和錄入資料 我這裡寫了一個公用的類,你給一個物件,告訴我按年還是按月生成表,並告訴我那個欄位是不需要在表

springboot整合hibernate自動建立資料庫

新建一個maven專案,我習慣性的建web了,有些依賴是沒必要的,主要用到的依賴有:                     <dependency><groupId>org.springframework.boot</groupId>&l

Springboot專案啟動後自動建立關聯的資料庫與的方案

文/朱季謙   熬夜寫完,尚有不足,但仍在努力學習與總結中,而您的點贊與關注,是對我最大的鼓勵!   在一些專案開發當中,存在這樣一種需求,即開發完成的專案,在第一次部署啟動時,需能自行構建系統需要的資料庫及其對應的資料庫表。 若要解決這類需求,其實現在已有不少開源框架都能實現自動生成資料

使用hibernate自動建立Mysql失敗原因及解決方法

原因: hibernate裡的dialect和Mysql的版本不匹配,SQL語句裡的type=“****”使用在MySQL5.0之前,5.0之後就要是使用engine=“****”。 解決: 修改hibernate.cfg.xml檔案 MySql5.0之前的配置 <property

建立資料

SQL語句CREATE TABLE 用於建立資料表,其基本語法如下: CREATE TABLE 表名 ( 欄位名1 欄位型別, 欄位名2 欄位型別, 欄位名3 欄位型別, ……………… 約束定義 1, 約束定義 2, ……………… ) 這裡的CREATE TABLE

Mysql01伺服器概述、資料庫伺服器、建立資料庫、建立資料

Mysql資料庫 day01 資料庫  儲存資料  MySQL、oracle、sql server、db2、sqlite…  關係型資料庫  資料以表格形式存放  No sql Mysql  開源免費資料庫  在網際網路領域,是最常用的資料庫  被 sun 以10

springboot mybatis自動生成程式碼外掛

springboot整合mybatis後,安裝generator外掛自動生成程式碼 首先,修改pom檔案,新增依賴: <dependency> <groupId>org.mybatis.generator</groupId>

建立資料例子

--建立資料表 create table biz_data_chg ( serno varchar2(32 byte) not null, mod_type varchar2(2 byte), loan_fee

關於建立資料的問題

比如這條建立表的sql create table `db_goods` ( `id` bigint unsigned not null AUTO_INCREMENT comment '主鍵', `goods_id` int(11) unsigned not null comment

吳裕雄 08-MySQL建立資料

MySQL 建立資料表建立MySQL資料表需要以下資訊:表名表字段名定義每個表字段 語法以下為建立MySQL資料表的SQL通用語法:CREATE TABLE table_name (column_name column_type); 以下例子中我們將在 RUNOOB 資料庫中建立資料表runoob_tbl

MySQL建立資料和MySQL資料型別

CREATE TABLE IF NOT EXISTS dmdi.bond_sentiment_news( `id` int(12) NOT NULL COMMENT 'id', `title` varchar(480) NULL DEFAULT NULL

(六)springboot + mybatis plus實現多聯查分頁3.X版本

註明 : 上兩篇文章我們講解了springboot+mybatis-plus對於單表的CRUD和條件構造器的使用方法,但是對於我們的實戰專案中多表聯查也是經常會出現的。今天我們就來說下怎麼在springboot+MP模式下實現多表聯查並分頁。 MP推薦使用的是

3)-MySQL建立資料

MySQL 建立資料表 建立MySQL資料表需要以下資訊: 表名 表字段名 定義每個表字段 語法 以下為建立MySQL資料表的SQL通用語法:   create table table_name (column_name column_type);

關於使用python來實現mysql自動生成資料

注:環境 windows 7 旗艦版 python 3.6.4 xlrd模組 pymysql模組 mysql 8.0.12 前幾天拿到一個專案需要在資料庫建立‘一堆’的表!於是就有了一個偷懶的想法! 經過努力終於完成了‘乞丐版’程式碼如下: # -*-

自動建立資料夾 pictureBox 顯示圖片 並呼叫系統窗體開啟資料

設定pictureBox1 圖片自適應: SizeMode:StretchImage BackgroundImagelayout : Stretch; 點選開啟檔案效果如下: 程式碼實現: using System; using System.Collect

laravel使用Schema建立資料

1、簡介 遷移就像資料庫的版本控制,允許團隊簡單輕鬆的編輯並共享應用的資料庫表結構,遷移通常和Laravel的schema構建器結對從而可以很容易地構建應用的資料庫表結構。如果你曾經告知小組成員需要手動新增列到本地資料庫結構,那麼這正是資料庫遷移所致力於解決的問題。 Laravel 的Schema

PHP與MySQL互動——建立資料

建立一個名User的資料表 SQL語句為: CREATE TABLE User (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20) NOT NULL, password VARCHAR(20) NO