mybatis 创建mysql表_SpringBoot+Mybatis 自动创建数据表

本文介绍了如何使用SpringBoot和Mybatis实现自动根据实体类创建MySQL数据表,包括三个阶段的演变,从Mybatis-Generator到无XML的Mybatis,再到使用通用Mapper。文章提供了一个基于SpringBoot的简单Demo,并分享了自动创建表的配置和实体类注解的使用。
摘要由CSDN通过智能技术生成

下面的信息是旧版的哦,代码有一些是不能用的~

Mybatis和Hibernate是两个比较热门的持久层框架。使用起来也各有利弊(个人使用了几个月的Hibernate后还是决定回到Mybatis的怀抱)

25db002b0367

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,建议去看此框架开发者写的博文)

SpringBoot整合A.CTable

项目目录

- com

- config

- MyBatisMapperScannerConfig.java

- TestConfig.java

- entity

- Test.java

- mapper

- TestMapper.java

- DemoApplication.java

依赖包

com.gitee.sunchenbin.mybatis.actable

mybatis-enhance-actable

1.0.3

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目录

要是对你有用就点个赞把~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值