欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot+mybatis通過實體類自動生成數(shù)據(jù)庫表的方法

 更新時間:2020年07月09日 11:48:05   作者:Dlei東  
這篇文章主要介紹了springboot+mybatis通過實體類自動生成數(shù)據(jù)庫表的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

本章介紹使用mybatis結(jié)合mysql數(shù)據(jù)庫自動根據(jù)實體類生成相關的數(shù)據(jù)庫表。

首先引入相關的pom包我這里使用的是springboot2.1.8.RELEASE的版本

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.0</version>
</dependency>
<dependency>
	<groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
	<artifactId>mybatis-enhance-actable</artifactId>
	<version>1.0.1</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.10</version>
</dependency>

<!--以下兩個類需要加入,否則報錯無法注入-->
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.4</version>
</dependency>
<dependency>
	<groupId>net.sf.json-lib</groupId>
	<artifactId>json-lib</artifactId>
	<version>2.4</version>
	<classifier>jdk15</classifier>
	<exclusions>
		<exclusion>
			<artifactId>commons-logging</artifactId>
			<groupId>commons-logging</groupId>
		</exclusion>
	</exclusions>
</dependency>

添加數(shù)據(jù)庫配置文件application.properties
application.properties這里是單獨配置mybatis自動建表的相關信息。

mybatis.table.auto=update
mybatis.model.pack=com.xxx.xxx.entity//實體類的路徑
mybatis.database.type=mysql

mybatis.table.auto=

create:
每次加載hibernate會自動創(chuàng)建表,以后啟動會覆蓋之前的表,所以這個值基本不用,嚴重會導致的數(shù)據(jù)的丟失。

create-drop :
每次加載hibernate時根據(jù)model類生成表,但是sessionFactory一關閉,表就自動刪除,下一次啟動會重新創(chuàng)建。

update:
加載hibernate時根據(jù)實體類model創(chuàng)建數(shù)據(jù)庫表,這是表名的依據(jù)是@Entity注解的值或者@Table注解的值,sessionFactory關閉表不會刪除,且下一次啟動會根據(jù)實體。

model:
更新結(jié)構(gòu)或者有新的實體類會創(chuàng)建新的表。

validate:
啟動時驗證表的結(jié)構(gòu),不會創(chuàng)建表 none:啟動時不做任何操作

mybatis.model.pack=com.xxx.xxx.entity//你實體類的路徑

個人項目配置文件,非統(tǒng)一,根據(jù)項目需求配置

進行生成數(shù)據(jù)庫表相關配置

TestConfig配置文件

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"})//固定的包
public class TestConfig {
	//連接數(shù)據(jù)庫配置文件的地址,具體查閱配置文件的結(jié)構(gòu)
 @Value("${spring.datasource.druid.driver-class-name}")
 private String driver;
	//連接數(shù)據(jù)庫配置文件的地址,具體查閱配置文件的結(jié)構(gòu)
 @Value("${spring.datasource.druid.url}")
 private String url;
	//連接數(shù)據(jù)庫配置文件的地址,具體查閱配置文件的結(jié)構(gòu)
 @Value("${spring.datasource.druid.username}")
 private String username;
	//連接數(shù)據(jù)庫配置文件的地址,具體查閱配置文件的結(jié)構(gòu)
 @Value("${spring.datasource.druid.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"));//classpath*:application.properties是mybatis的生成表配置文件
 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.xxx.xxx.entity.*");
 //上述classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml固定的包路徑
 //com.xxx.xxx.entity.*替換成你的實體類地址
 return sqlSessionFactoryBean;
 }
}

MyBatisMapperScannerConfig配置文件

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AutoConfigureAfter(TestConfig.class)//上面第一點配置文件類
public class MyBatisMapperScannerConfig {

 @Bean
 public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{
  MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
   mapperScannerConfigurer.setBasePackage("com.xxx.xxx.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*");
  mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
  //com.xxx.xxx.mapper.*替換成你的mapper地址
  //com.gitee.sunchenbin.mybatis.actable.dao.*固定的包
  return mapperScannerConfigurer;
 }

}

新建實體進行測試

注:@Table(name = “”)及@Column(name = “id”)注解使用,實體類繼承BaseModel。

import com.gitee.sunchenbin.mybatis.actable.annotation.Column;
import com.gitee.sunchenbin.mybatis.actable.annotation.Table;
import com.gitee.sunchenbin.mybatis.actable.command.BaseModel;
import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant;

@Table(name = "em_t")//新建表數(shù)據(jù)庫表名
public class EmpAttr extends BaseModel{
 private static final long serialVersionUID = 5199244153134426433L;

 @Column(name = "id",type = MySqlTypeConstant.INT,length = 11,isKey = true,isAutoIncrement = true)
 private String id;

 @Column(name="ename",type= MySqlTypeConstant.VARCHAR)
 private String ename;

 @Column(name="sal",type= MySqlTypeConstant.VARCHAR)
 private String sal;

 @Column(name="job",type= MySqlTypeConstant.VARCHAR)
 private String job;

 //...省略get,set方法
}

運行項目

會控制臺會顯示說新建表完成
2020-07-08 11:02:13.895 INFO 48536 — [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 開始創(chuàng)建表:em_t
2020-07-08 11:02:13.983 INFO 48536 — [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 完成創(chuàng)建表:em_t

 . ____   _   __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.1.8.RELEASE)

2020-07-08 11:02:11.264 INFO 48536 --- [   main] com.qiaoyuantest.www.WwwApplication  : Starting WwwApplication on DD-HP with PID 48536 (E:\mysoft\kaifasoft\kaifa_code\idea\myiperf_springboot\target\classes started by DD in E:\mysoft\kaifasoft\kaifa_code\idea\myiperf_springboot)
2020-07-08 11:02:11.266 INFO 48536 --- [   main] com.qiaoyuantest.www.WwwApplication  : The following profiles are active: prod
2020-07-08 11:02:12.207 INFO 48536 --- [   main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-07-08 11:02:12.208 INFO 48536 --- [   main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-07-08 11:02:12.228 INFO 48536 --- [   main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 repository interfaces.
2020-07-08 11:02:12.301 INFO 48536 --- [   main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance @Configuration bean definition 'myBatisMapperScannerConfig' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2020-07-08 11:02:12.522 INFO 48536 --- [   main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$54b62352] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-07-08 11:02:12.613 INFO 48536 --- [   main] trationDelegate$BeanPostProcessorChecker : Bean 'redisConfiguration' of type [com.qiaoyuantest.www.config.RedisConfiguration$$EnhancerBySpringCGLIB$$9518fca7] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-07-08 11:02:12.651 ERROR 48536 --- [   main] o.a.catalina.core.AprLifecycleListener : An incompatible version [1.2.7] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2020-07-08 11:02:12.808 ERROR 48536 --- [   main] o.a.catalina.core.AprLifecycleListener : An incompatible version [1.2.7] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2020-07-08 11:02:12.927 INFO 48536 --- [   main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8910 (http)
2020-07-08 11:02:12.937 ERROR 48536 --- [   main] o.a.catalina.core.AprLifecycleListener : An incompatible version [1.2.7] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
2020-07-08 11:02:12.937 INFO 48536 --- [   main] o.a.coyote.http11.Http11NioProtocol  : Initializing ProtocolHandler ["http-nio-8910"]
2020-07-08 11:02:12.944 INFO 48536 --- [   main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-07-08 11:02:12.944 INFO 48536 --- [   main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.24]
2020-07-08 11:02:13.035 INFO 48536 --- [   main] o.a.c.c.C.[Tomcat].[localhost].[/]  : Initializing Spring embedded WebApplicationContext
2020-07-08 11:02:13.036 INFO 48536 --- [   main] o.s.web.context.ContextLoader   : Root WebApplicationContext: initialization completed in 1732 ms
2020-07-08 11:02:13.623 INFO 48536 --- [   main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-07-08 11:02:13.676 INFO 48536 --- [   main] c.g.s.m.a.m.handler.StartUpHandlerImpl : databaseType=mysql,開始執(zhí)行mysql的處理方法
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2020-07-08 11:02:13.829 INFO 48536 --- [   main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
file類型的掃描
2020-07-08 11:02:13.895 INFO 48536 --- [   main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 開始創(chuàng)建表:em_t
2020-07-08 11:02:13.983 INFO 48536 --- [   main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 完成創(chuàng)建表:em_t
2020-07-08 11:02:14.002 INFO 48536 --- [   main] c.q.www.config.RedisConfiguration  : 自定義RedisCacheManager加載完成
2020-07-08 11:02:14.826 INFO 48536 --- [   main] o.a.coyote.http11.Http11NioProtocol  : Starting ProtocolHandler ["http-nio-8910"]
2020-07-08 11:02:14.849 INFO 48536 --- [   main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8910 (http) with context path ''
2020-07-08 11:02:14.851 INFO 48536 --- [   main] com.qiaoyuantest.www.WwwApplication  : Started WwwApplication in 4.162 seconds (JVM running for 4.863)


此時查看一下數(shù)據(jù)庫表會發(fā)現(xiàn)新建有em_t表


新建表就這樣完成。

如出現(xiàn)
Error creating bean with name ‘startUpHandlerImpl': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/lang/ArrayUtils錯誤


說明pom缺省包或者包不正確

<!--以下兩個類需要加入,否則報錯無法注入-->
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3</artifactId>
		<version>3.4</version>
	</dependency>
	<dependency>
		<groupId>net.sf.json-lib</groupId>
		<artifactId>json-lib</artifactId>
		<version>2.4</version>
		<classifier>jdk15</classifier>
		<exclusions>
			<exclusion>
				<artifactId>commons-logging</artifactId>
				<groupId>commons-logging</groupId>
			</exclusion>
		</exclusions>
	</dependency>

如需要項目源碼或者對代碼有疑問的評論留言,下期會動手實現(xiàn)mybatis plus內(nèi)嵌的CRUD自動增刪改查

到此這篇關于springboot+mybatis通過實體類自動生成數(shù)據(jù)庫表的方法的文章就介紹到這了,更多相關springboot mybatis實體類生成數(shù)據(jù)庫表內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • mybatis模糊查詢之bind標簽和concat函數(shù)用法詳解

    mybatis模糊查詢之bind標簽和concat函數(shù)用法詳解

    大家都知道bind 標簽可以使用 OGNL 表達式創(chuàng)建一個變量井將其綁定到上下文中,接下來通過本文給大家介紹了mybatis模糊查詢——bind標簽和concat函數(shù)用法,需要的朋友可以參考下
    2022-08-08
  • redis深入淺出分布式鎖實現(xiàn)上篇

    redis深入淺出分布式鎖實現(xiàn)上篇

    在單體應用中,如果我們對共享數(shù)據(jù)不進行加鎖操作,會出現(xiàn)數(shù)據(jù)一致性問題,我們的解決辦法通常是加鎖。下面我們一起聊聊使用redis來實現(xiàn)分布式鎖
    2022-08-08
  • SpringBoot借助spring.factories文件跨模塊實例化Bean

    SpringBoot借助spring.factories文件跨模塊實例化Bean

    這篇文章主要介紹了SpringBoot借助spring.factories文件跨模塊實例化Bean,文章圍繞主題展開詳細的內(nèi)容介紹,需要的小伙伴可以參考一下
    2022-04-04
  • Java處理Webp圖片格式轉(zhuǎn)換的示例代碼

    Java處理Webp圖片格式轉(zhuǎn)換的示例代碼

    這篇文章主要介紹了Java處理Webp圖片格式轉(zhuǎn)換的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-09-09
  • 教你bat腳本一鍵配置java開發(fā)環(huán)境

    教你bat腳本一鍵配置java開發(fā)環(huán)境

    公司新入職一名員工,項目經(jīng)理讓我安排新人工作,首先需要對java開發(fā)相關環(huán)境進行配置安裝,但時常會因為安裝配置不到位或者操作錯誤導致時間的浪費,所以在空余時間收集了一系列軟件的免安裝版本,感興趣的朋友一起看看吧
    2021-12-12
  • Java?HashMap中除了死循環(huán)之外的那些問題

    Java?HashMap中除了死循環(huán)之外的那些問題

    這篇文章主要介紹了Java?HashMap中除了死循環(huán)之外的那些問題,這些問題大致可以分為兩類,程序問題和業(yè)務問題,下面文章我們一個一個來看,需要的小伙伴可以參考一下
    2022-05-05
  • Java 實戰(zhàn)項目錘煉之在線美食網(wǎng)站系統(tǒng)的實現(xiàn)流程

    Java 實戰(zhàn)項目錘煉之在線美食網(wǎng)站系統(tǒng)的實現(xiàn)流程

    讀萬卷書不如行萬里路,只學書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+jsp+mysql+maven實現(xiàn)一個在線美食網(wǎng)站系統(tǒng),大家可以在過程中查缺補漏,提升水平
    2021-11-11
  • 關于@Autowired注入依賴失敗的問題及解決

    關于@Autowired注入依賴失敗的問題及解決

    這篇文章主要介紹了關于@Autowired注入依賴失敗的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • 詳解如何在Spring?Security中自定義權(quán)限表達式

    詳解如何在Spring?Security中自定義權(quán)限表達式

    這篇文章主要和大家詳細介紹一下如何在Spring?Security中自定義權(quán)限表達式,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2022-07-07
  • Java訪問權(quán)限控制的重要性深入講解

    Java訪問權(quán)限控制的重要性深入講解

    這篇文章主要給大家介紹了關于Java訪問權(quán)限控制的重要性的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-11-11

最新評論