javascript
Springboot,Mybatis根据实体类自动建表
Springboot,Mybatis根據實體類自動建表
在創建實體類的同時還要在數據庫建表,如果只是很少的屬性那么無所謂,但是當實體類很多或者字段很多時這就是一個非常讓人不爽的事情了
通常有兩種思路,一種是根據數據庫來自動創建實體類,這個mybatis-generator已經提供了方法
還有一種思路就是根據實體類來自動建立表格
這里需要用到A.CTable框架,也就是mybatis-enhance-actable
一個小Demo,一步步來
首先添加依賴項
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.17</version></dependency><!-- 添加mybatis依賴 --><!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency><!--添加A.CTable框架 --><dependency><groupId>com.gitee.sunchenbin.mybatis.actable</groupId><artifactId>mybatis-enhance-actable</artifactId><version>1.0.3</version></dependency><!-- 阿里系的Druid依賴包 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.9</version></dependency><!-- Druid 依賴 log4j包 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency>項目結構如下
然后在application.yml文件里添加配置信息
#服務配置 server:port: 8080spring:#數據庫配置datasource:username: yourusernamepassword: yourpassworddriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://yoururl#阿里druid連接池驅動配置信息type: com.alibaba.druid.pool.DruidDataSource#連接池的配置信息druid:#初始化大小,最小,最大initial-size: 2#A.CTable配置 mybatis:#自動更新表table:auto: true#實體類掃描地址model:pack: com.boot_demo.demo1.entity#數據庫類型 database:type: mysql下面開始寫配置信息
@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;@Beanpublic YamlPropertiesFactoryBean configProperties() throws Exception{YamlPropertiesFactoryBean propertiesFactoryBean = new YamlPropertiesFactoryBean();PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();propertiesFactoryBean.setResources(resolver.getResources("classpath*:application.yml"));return propertiesFactoryBean;}@Beanpublic 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;}@Beanpublic DataSourceTransactionManager dataSourceTransactionManager() {DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();dataSourceTransactionManager.setDataSource(dataSource());return dataSourceTransactionManager;}@Beanpublic 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 {@Beanpublic MapperScannerConfigurer mapperScannerConfigurer() throws Exception{MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage("com.example.dao.*;com.gitee.sunchenbin.mybatis.actable.dao.*");mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");return mapperScannerConfigurer;} }下面創建實體類
根據Column注解在數據庫創建指定的結構
如果指定了某個字段為主鍵且要自增,那么該字段必須為Integer-MySqlTypeConstant.INT且需要在Column注解中添加如下屬性
isKey = true,isAutoIncrement = truemybatis-enhance-actable本身BaseMysqlCRUDManager提供了根據實體類進行簡單增刪改查的方法,當然如果有特殊需要還是要自己寫mapper映射的,這里就不寫了,來看看它提供的基礎方法
先寫dao層
@Repository public class TestDao {@Autowiredprivate BaseMysqlCRUDManager baseMysqlCRUDManager;public void delete(Test test){baseMysqlCRUDManager.delete(test);}public void insert(Test test){baseMysqlCRUDManager.save(test);} }然后寫一下service層
@Service public class TestServiceImpl implements TestService {@Autowiredprivate TestDao testDao;@Overridepublic void insert(Test test) {testDao.insert(test);}@Overridepublic void delete(Test test) {testDao.delete(test);} }controller層
@RestController @RequestMapping("/test") public class TestController {@Autowiredprivate TestService testService;@RequestMapping("/hello")public String hello(){return "hello";}@RequestMapping("/add")public String add(){Test test=new Test();test.setId(UUID.randomUUID().toString());test.setValue("插入測試");test.setComment("插入測試");try {testService.insert(test);} catch (Exception e) {e.printStackTrace();return "failed";}return "success";}@RequestMapping("/remove")public String remove(){Test test=new Test();test.setId("1b2c3d4e");try {testService.delete(test);} catch (Exception e) {e.printStackTrace();return "failed";}return "success";} }下面啟動項目,我們可以看到控制臺日志出現這樣的信息
這就代表數據庫表已經建立成功了
如果控制臺出現ClassNotFound:apache.common.lang.ArrayUtils的報錯,就需要再添加一下依賴
下面測試一下add和delete方法
我先在數據庫中添加數據
數據添加成功
數據刪除成功
參考文章
spring-boot + mybatis-enhance-actable 實現mybatis自動建表
SpringBoot+Mybatis 自動創建數據表
總結
以上是生活随笔為你收集整理的Springboot,Mybatis根据实体类自动建表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java数据库插入记录的语句-单引号-双
- 下一篇: DOS运行GHOST加参数