slug: mybatis status: Published type: Post
使用过程
SpringBoot Mybatis入手项目:SpringBoot Mybatis
SpringBoot+Mybatis+Oracle(Mysql)配置:
Spring Initializer:Mybatis、Oracle Driver. 引入以下依赖。主要是SpringBoot Mybatis、ojdbc、lombok用来编写entity、orail8n解决:不支持的字符集 (在类路径中添加 orai18n.jar): ZHS16GBK。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
<!-- 引入 MyBatis 场景启动器,包含其自动配置类及 MyBatis 相关依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc8</artifactId> <scope>runtime</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.oracle.database.nls/orai18n --> <dependency> <groupId>com.oracle.database.nls</groupId> <artifactId>orai18n</artifactId> <version>19.7.0.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
application.properties中添加SpringBoot Mybatis的数据库配置。主要是数据库信息,以及mapper的路径。
1 2 3 4 5 6 7
# datasource config spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl spring.datasource.username=LJH spring.datasource.password= mybatis.mapper-locations=classpath:mapper/*Dao.xml # 改为自己匹配的
创建对应的Mapper、Entity。
1 2 3 4
@Mapper public interface SQLQueryDao { List<SQLScene> selectAllScenes(); }
1 2 3 4 5 6
@Data public class SQLScene { Integer id; String name; String sql_statement; }
可以通过在SpringBootApplication中添加Scanner,不用注释mapper。
1 2 3 4 5 6 7 8 9
@SpringBootApplication @MapperScan("com.example.generalquerygenerationback.dao") public class GeneralQueryGenerationBackApplication { public static void main(String[] args) { SpringApplication.run(GeneralQueryGenerationBackApplication.class, args); } }
编写对应的mapper.xml. 这是最可能出现问题的地方。以上步骤都相对固定且很简单。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.generalquerygenerationback.dao.SQLQueryDao"> <!-- SQLScene 对应的 resultMap --> <resultMap id="SQLSceneResultMap" type="com.example.generalquerygenerationback.entity.SQLScene"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="sql_statement" property="sql_statement"/> </resultMap> <!-- 查询所有场景信息 --> <select id="selectAllScenes" resultMap="SQLSceneResultMap"> SELECT ID, NAME, SQL_STATEMENT FROM LJH.sql_scene </select> </mapper>
坑:
- 记得mapper、entity定义的路径和mapper.xml中一定要对应,检查好路径。mapper和entity中定义的接口和数据变量也要一一对应。
- 注意SQL语句最后不能带分号,否则:【java】 java.sql.SQLException: ORA-00911: 无效字符的问题。
需求
JSONHandler处理数组或map
ORM映射储存对象中包含数组或Map键值对的属性时,通过JSONHandler进行序列化和反序列化,这里只针对最简单的情况,就是储存一队键值对。