MyBatis-plus+達夢數(shù)據(jù)庫實現(xiàn)自動生成代碼的示例
先說點什么
mybatis-plus是一款增強版的mybatis,功能強大,可以很大程度的簡化開發(fā)。然而達夢數(shù)據(jù)庫比較小眾,雖然官方說mybatis-plus支持達夢數(shù)據(jù)庫,但是使用起來遇到了很多問題。這篇文章主要講如何使用mybatis-plus訪問達夢數(shù)據(jù)庫,并使用逆向工程自動生成代碼。=。=對了 這是個使用spring boot的項目。
(配置)POM文件,引入所需要的依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions><exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId></exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.29</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.2.0.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-test</artifactId> </dependency> </dependencies>
(配置)達夢的驅(qū)動包,配置數(shù)據(jù)源
在達夢數(shù)據(jù)庫的安裝目錄下有驅(qū)動包,我們先把jar包丟進來,放到lib這個文件夾下:
然后配置pom文件:
<dependency> <groupId>com.dm</groupId> <artifactId>Dm7JdbcDriver</artifactId> <version>1.7</version> <scope>system</scope> <systemPath>${project.basedir}/src/lib/Dm7JdbcDriver18.jar</systemPath> </dependency>
到現(xiàn)在,所有需要的依賴就都已經(jīng)導(dǎo)入了。
(配置)application.properties文件
spring.datasource.url=spring.datasource.username=spring.datasource.password=spring.datasource.driver-class-name=dm.jdbc.driver.DmDrivermybatis-plus.configuration.cache-enabled=truemybatis-plus.mapper-locations=classpath*:mappers/*.xmlmybatis-plus.type-aliases-package=com.example.demo.extity.*mybatis-plus.configuration.map-underscore-to-camel-case=truemybatis-plus.configuration.auto-mapping-behavior=fullmybatis-plus.global-config.banner=false
創(chuàng)建Mybatis-Plus自動生成代碼的配置類
在配置數(shù)據(jù)源的時候要注意,如果不設(shè)置數(shù)據(jù)源的類型是達夢數(shù)據(jù)庫,會無法識別。經(jīng)歷了開心的看源碼環(huán)節(jié),我們發(fā)現(xiàn)Mybatis中有個枚舉類DbType來標識數(shù)據(jù)庫的類型,其中有達夢數(shù)據(jù)庫的類型。(=。=竟然有)所以我們在配置類里傳個參數(shù)就好了。(=。= 不然可能就涼了)
dsc.setDbType(DbType.DM);
配置類代碼:
public class MysqlGenerator { public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append('請輸入' + tip + ':'); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) {return ipt; } } throw new MybatisPlusException('請輸入正確的' + tip + '!'); } public static void main(String[] args) { // 代碼生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty('user.dir'); gc.setOutputDir(projectPath + '/src/main/java'); gc.setAuthor('kning'); gc.setOpen(false); gc.setSwagger2(true); gc.setIdType(IdType.AUTO); gc.setBaseResultMap(true); mpg.setGlobalConfig(gc);//達夢數(shù)據(jù)庫的配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.DM); dsc.setSchemaName('SYSDBA'); dsc.setUrl(''); dsc.setDriverName('dm.jdbc.driver.DmDriver'); dsc.setUsername(''); dsc.setPassword(''); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner('模塊名')); pc.setParent('com.example'); mpg.setPackageInfo(pc);// 自定義配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() {// to do nothing } }; List<FileOutConfig> focList = new ArrayList<>(); focList.add(new FileOutConfig('/templates/mapper.xml.ftl') { @Override public String outputFile(TableInfo tableInfo) {// 自定義輸入文件名稱return projectPath + '/src/main/resources/mapper/' + pc.getModuleName() + '/' + tableInfo.getEntityName() + 'Mapper' + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null));// 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setInclude(scanner('表名')); strategy.setSuperEntityColumns('id'); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + '_'); strategy.setEntityLombokModel(true); mpg.setStrategy(strategy); // 選擇 freemarker 引擎需要指定如下加,注意 pom 依賴必須有! mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); }}
Mybatis-plus生成代碼
首先我們在數(shù)據(jù)庫里創(chuàng)建一張表,就叫教師(teacher)表好了。達夢數(shù)據(jù)庫似乎要求表名盡量是大寫的。
然后插入一點數(shù)據(jù)方便測試。
運行測試類,輸入模塊名和表名,達夢數(shù)據(jù)庫要求表名是大寫的。
不出意外,我們就生成成功了。=。=不要問為什么有個students,因為自己測試用的這個。
測試一下
我們來簡單寫個測試類,其功能是查出教師表的所有數(shù)據(jù),然后插入一條教師信息,然后在查一次:
@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTestpublic class teacherTest { @Autowired private TeacherMapper teacherMapper; @Test public void teacher(){ List<Teacher> teachers = teacherMapper.selectList(null); teachers.forEach(System.out::println); System.out.println('=================================='); Teacher teacher = new Teacher(); teacher.setId(6); teacher.setName('zhou'); teacher.setAge(58); teacherMapper.insert(teacher); teachers = teacherMapper.selectList(null); teachers.forEach(System.out::println); }}
=。=看樣子我們成功了。
到這里,我們就成功的使用Mybatis-plus成功的生成了代碼。
Mybatis-plus主鍵生成可能出現(xiàn)的問題
讓我們來看看錯誤信息:
org.springframework.dao.DataIntegrityViolationException: ### Error updating database. Cause: java.sql.SQLException: 違反列[ID]非空約束### The error may exist in com/example/demo/mapper/TeacherMapper.java (best guess)### The error may involve com.example.demo.mapper.TeacherMapper.insert-Inline### The error occurred while setting parameters### SQL: INSERT INTO TEACHER ( NAME, AGE ) VALUES ( ?, ? )### Cause: java.sql.SQLException: 違反列[ID]非空約束
很顯然,是主鍵插入時的問題。我們看一下mybatis-plus生成的實體類。
@TableId(value = 'ID', type = IdType.AUTO) private Integer id;
其中ID的屬性設(shè)置為自動,然而如果達夢數(shù)據(jù)庫建表的時候如果沒有設(shè)置主鍵為自增。=。= 那沒準就涼了。我們看一下mybatis-plus支持哪些屬性:
@Getterpublic enum IdType { /** * 數(shù)據(jù)庫ID自增 */ AUTO(0), /** * 該類型為未設(shè)置主鍵類型(將跟隨全局) */ NONE(1), /** * 用戶輸入ID * <p>該類型可以通過自己注冊自動填充插件進行填充</p> */ INPUT(2), /* 以下3種類型、只有當插入對象ID 為空,才自動填充。 */ /** * 全局唯一ID (idWorker) */ ID_WORKER(3), /** * 全局唯一ID (UUID) */ UUID(4), /** * 字符串全局唯一ID (idWorker 的字符串表示) */ ID_WORKER_STR(5); private final int key; IdType(int key) { this.key = key; }}
可以看出,解決這個問題最簡單的方法就是,修改IdType,使用NONE,自己傳入id(主鍵)。同樣的,在自動生成代碼的階段,我們曾經(jīng)設(shè)置過
gc.setIdType(IdType.AUTO);
在這里更改可以直接更改自動生成的代碼,甚至也可以選擇UUID等方式。當然,這樣并不好,所以也可以修改數(shù)據(jù)庫表,設(shè)置ID為自增。在剛剛的teacher表中執(zhí)行下面這條語句,就可以修改主鍵id的屬性為自增了。
ALTER TABLE TEACHER ADD ID identity (1,1);
然后在運行代碼,多半就成了。
到此這篇關(guān)于MyBatis-plus+達夢數(shù)據(jù)庫實現(xiàn)自動生成代碼的示例的文章就介紹到這了,更多相關(guān)MyBatis-plus 自動生成代碼內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 如何:創(chuàng)建和運行 CLR SQL Server 用戶定義的類型2. 快速刪除ORACLE重復(fù)記錄3. Windows下不能啟動mysql服務(wù)--錯誤總結(jié)4. 數(shù)據(jù)庫相關(guān)的幾個技能:ACCESS轉(zhuǎn)SQL5. MySQL性能壓力基準測試工具sysbench的使用簡介6. Mysql故障排除:Starting MySQL. ERROR! Manager of pid-file quit without updating file7. 如何安裝MySQL 壓縮包8. mysql啟動時報錯 ERROR! Manager of pid-file quit without9. mysql innodb的重要組件匯總10. 如何實現(xiàn)MySQL數(shù)據(jù)庫的備份與恢復(fù)
