日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Springboot,Mybatis根据实体类自动建表

發布時間:2024/3/13 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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注解在數據庫創建指定的結構

@Table(name="test") public class Test {@Column(name="id",type= MySqlTypeConstant.VARCHAR)private String id;@Column(name="value",type = MySqlTypeConstant.VARCHAR)private String value;@Column(name="comment",type = MySqlTypeConstant.VARCHAR)private String comment;}

如果指定了某個字段為主鍵且要自增,那么該字段必須為Integer-MySqlTypeConstant.INT且需要在Column注解中添加如下屬性

isKey = true,isAutoIncrement = true

mybatis-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的報錯,就需要再添加一下依賴

<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang --><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency>

下面測試一下add和delete方法
我先在數據庫中添加數據



數據添加成功


數據刪除成功

參考文章
spring-boot + mybatis-enhance-actable 實現mybatis自動建表
SpringBoot+Mybatis 自動創建數據表

總結

以上是生活随笔為你收集整理的Springboot,Mybatis根据实体类自动建表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。