springboot+mybatis通过实体类⾃动⽣成数据库表的⽅法
前⾔
本章介绍使⽤mybatis结合mysql数据库⾃动根据实体类⽣成相关的数据库表。
⾸先引⼊相关的pom包我这⾥使⽤的是springboot2.1.8.RELEASE的版本
<dependency>
<groupId&batis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.batis.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.apachemons</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=update
pe=mysql
mybatis.table.auto=
create:
每次加载hibernate会⾃动创建表,以后启动会覆盖之前的表,所以这个值基本不⽤,严重会导致的数据的丢失。
create-drop :
每次加载hibernate时根据model类⽣成表,但是sessionFactory⼀关闭,表就⾃动删除,下⼀次启动会重新创建。
update:
加载hibernate时根据实体类model创建数据库表,这是表名的依据是@Entity注解的值或者@Table注
解的值,sessionFactory关闭表不会删除,且下⼀次启动会根据实体。model:
更新结构或者有新的实体类会创建新的表。
validate:
启动时验证表的结构,不会创建表 none:启动时不做任何操作
个⼈项⽬配置⽂件,⾮统⼀,根据项⽬需求配置
进⾏⽣成数据库表相关配置
TestConfig配置⽂件
import com.alibaba.druid.pool.DruidDataSource;
batis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.fig.PropertiesFactoryBean;
import t.annotation.Bean;
import t.annotation.ComponentScan;
import t.annotation.Configuration;
import io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@Configuration
@ComponentScan(basePackages = {"com.batis.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.Resources("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.Resources("classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("tity.*");
//上述classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml固定的包路径
//tity.*替换成你的实体类地址
return sqlSessionFactoryBean;
}
}
MyBatisMapperScannerConfig配置⽂件
batis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import t.annotation.Bean;
import t.annotation.Configuration;
@Configuration
@AutoConfigureAfter(TestConfig.class)//上⾯第⼀点配置⽂件类
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("apper.*;com.batis.actable.dao.*");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//apper.*替换成你的mapper地址
//com.batis.actable.dao.*固定的包
return mapperScannerConfigurer;
}
}
新建实体进⾏测试
注:@Table(name = “”)及@Column(name = “id”)注解使⽤,实体类继承BaseModel。
import com.batis.actable.annotation.Column;
import com.batis.actable.annotation.Table;
import com.batis.actablemand.BaseModel;
import com.stants.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.s.SysMysqlCreateTableManagerImpl : 开始创建表:em_t
2020-07-08 11:02:13.983 INFO 48536 — [ main] s.s.SysMysqlCreateTableManagerImpl : 完成创建表: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_c 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] .RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
springboot结构2020-07-08 11:02:12.208 INFO 48536 --- [  main] .RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2020-07-08 11:02:12.228 INFO 48536 --- [  main] .RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 repository interfaces.
2020-07-08 11:02:12.301 INFO 48536 --- [  main] a.ConfigurationClassPostProcessor : Cannot enhance @Configuration bean definition 'myBatisMapperScannerConfig' since its singleton instance has been created too early. The typical cause is a non-stat 2020-07-08 11:02:12.522 INFO 48536 --- [  main] trationDelegate$BeanPostProcessorChecker : Bean 'ansaction.annot
ation.ProxyTransactionManagementConfiguration' of type [ansaction.annotation.ProxyTransactio 2020-07-08 11:02:12.613 INFO 48536 --- [  main] trationDelegate$BeanPostProcessorChecker : Bean 'redisConfiguration' of type [com.fig.RedisConfiguration$$EnhancerBySpringCGLIB$$9518fca7] is not eligible for getting processed by a 2020-07-08 11:02:12.651 ERROR 48536 --- [  main] o.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.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.at.TomcatWebServer : Tomcat initialized with port(s): 8910 (http)
2020-07-08 11:02:12.937 ERROR 48536 --- [  main] o.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] http11.Http11NioProtocol  : Initializing ProtocolHandler ["http-nio-8910"]
2020-07-08 11:02:12.944 INFO 48536 --- [  main] o.StandardService : Starting service [Tomcat]
2020-07-08 11:02:12.944 INFO 48536 --- [  main] org.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.24]
2020-07-08 11:02:13.035 INFO 48536 --- [  main] C.[Tomcat].[localhost].[/]  : Initializing Spring embedded WebApplicationContext
2020-07-08 11:02:13.036 INFO 48536 --- [  main] o.t.ContextLoader  : Root WebApplicationContext: initialization completed in 1732 ms
2020-07-08 11:02:13.623 INFO 48536 --- [  main] o.urrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-07-08 11:02:13.676 INFO 48536 --- [  main] c.a.m.handler.StartUpHandlerImpl : databaseType=mysql,开始执⾏mysql的处理⽅法
Loading class `sql.jdbc.Driver'. This is deprecated. The new driver class is `sql.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.s.SysMysqlCreateTableManagerImpl : 开始创建表:em_t
2020-07-08 11:02:13.983 INFO 48536 --- [  main] s.s.SysMysqlCreateTableManagerImpl : 完成创建表:em_t
2020-07-08 11:02:14.002 INFO 48536 --- [  main] c.fig.RedisConfiguration  : ⾃定义RedisCacheManager加载完成
2020-07-08 11:02:14.826 INFO 48536 --- [  main] http11.Http11NioProtocol  : Starting ProtocolHandler ["http-nio-8910"]
2020-07-08 11:02:14.849 INFO 48536 --- [  main] o.s.at.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)
此时查看⼀下数据库表会发现新建有em_t表
新建表就这样完成。
如出现
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.apachemons</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>
如需要项⽬源码或者对代码有疑问的评论留⾔,下期会动⼿实现mybatis plus内嵌的CRUD⾃动增删改查
到此这篇关于springboot+mybatis通过实体类⾃动⽣成数据库表的⽅法的⽂章就介绍到这了,更多相关springboot mybatis实体类⽣成数据库表内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。