springboot+mybatis通过实体类自动生成数据库表的方法

时间:2021-05-19

前言

本章介绍使用mybatis结合mysql数据库自动根据实体类生成相关的数据库表。

首先引入相关的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>

添加数据库配置文件application.properties
application.properties这里是单独配置mybatis自动建表的相关信息。

mybatis.table.auto=updatemybatis.model.pack=com.xxx.xxx.entity//实体类的路径mybatis.database.type=mysql

mybatis.table.auto=

create:
每次加载hibernate会自动创建表,以后启动会覆盖之前的表,所以这个值基本不用,严重会导致的数据的丢失。

create-drop :
每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除,下一次启动会重新创建。

update:
加载hibernate时根据实体类model创建数据库表,这是表名的依据是@Entity注解的值或者@Table注解的值,sessionFactory关闭表不会删除,且下一次启动会根据实体。

model:
更新结构或者有新的实体类会创建新的表。

validate:
启动时验证表的结构,不会创建表 none:启动时不做任何操作

mybatis.model.pack=com.xxx.xxx.entity//你实体类的路径

个人项目配置文件,非统一,根据项目需求配置

进行生成数据库表相关配置

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 { //连接数据库配置文件的地址,具体查阅配置文件的结构 @Value("${spring.datasource.druid.driver-class-name}") private String driver; //连接数据库配置文件的地址,具体查阅配置文件的结构 @Value("${spring.datasource.druid.url}") private String url; //连接数据库配置文件的地址,具体查阅配置文件的结构 @Value("${spring.datasource.druid.username}") private String username; //连接数据库配置文件的地址,具体查阅配置文件的结构 @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")//新建表数据库表名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 : 开始创建表:em_t
2020-07-08 11:02:13.983 INFO 48536 — [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 完成创建表:em_t

. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.1.8.RELEASE)2020-07-08 11:02:11.264 INFO 48536 --- [ main] com.qiaoyuantest.mons-logging</groupId> </exclusion> </exclusions> </dependency>

如需要项目源码或者对代码有疑问的评论留言,下期会动手实现mybatis plus内嵌的CRUD自动增删改查

到此这篇关于springboot+mybatis通过实体类自动生成数据库表的方法的文章就介绍到这了,更多相关springboot mybatis实体类生成数据库表内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章