SpringBoot整合mybatis
- 在pom.xml文件中导入依赖
<!-- 配置mybatis --> <dependency> <!-- springboot和mybatis继承中间件 --> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mybatis-generator-core反向生成java代码 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency>
-
配置application.properties
#Mybatis spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/travelling_guideling?useSSL=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root
- 创建一个mybatis-generator.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <!-- mybaties逆向生成xml配置 --> <generatorConfiguration> <!-- 数据库连接配置文件 --> <properties resource="application.properties"/> <context id="mysqlTables" targetRuntime="MyBatis3"> <!-- 生成的pojo,将implements SerializablePlugin --> <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/> <commentGenerator> <!--是否去除自动生成的注释 true:是,false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!-- 数据库连接URL、用户名、密码 --> <jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}"> </jdbcConnection> <!-- 默认false,把JDBC DECIMAL和NUMBERIC类型解析为Integer true:把JDBC DECIMAL和NUMERIC类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径, 如./src/main/java --> <javaModelGenerator targetPackage="cn.muriel.pojo" targetProject="./src/main/java"> <property name="enableSubPackages" value="true"/> <!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 对应的mapper.xml文件 --> <sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources"> <property name="enablesSubPackages" value="true"/> </sqlMapGenerator> <!-- 对应的Mapper接口类文件 --> <javaClientGenerator type="XMLMAPPER" targetPackage="cn.muriel.mapper" targetProject="./src/main/java"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 列出来要生成代码的所有表,这里配置的是不生成Example文件 --> <!-- domainObjectName:指生成文件的基本名称。若不指定,将根据tableName自动生成名称 enableCountByExample:表示是否应生成按语句计数的语句。此语句将返回表中与示例匹配的行数,默认为true enableDeleteByExample:表示是否应生成按示例删除语句。此语句允许在运行时生成许多不同的动态删除。默认为true。 enableUpdatebyExample:表示是否应生成示例语句的更新。此语句将更更新表中与示例匹配的行。如果为true,则还将生成示例"selective"语句更新。 "selective"语句只会更新record参数中的相应值为非null的列。默认值为true enableSelectByExample:表示是否应生成select by example语句。此语句允许在运行时生成许多不同的动态查询。默认为true --> <table tableName="user" enableCountByExample="false" enableDeleteByExample="false" enableUpdateByExample="false" enableSelectByExample="false" selectByPrimaryKeyQueryId="false"> <property name="userActualColumnNames" value="false"/> </table> </context> </generatorConfiguration>
- 创建一个GenMain类(自动生成指定数据库表的mapper.java、mapper.xml、pojo)
/** * ResourceUtils:Spring提供ResourceUtils工具类,他支持"classpath:"和"file:"的地址前缀,它能够从指定的地址加载文件资源 */ public class GenMain { public static void main(String[] args) { List<String> warnings = new ArrayList<>(); boolean overwrite = true; try { //获取resources文件下的方法 //String path = GenMain.class.getClassLoader().getResource("mybaties-generator.xml").getPath(); //获取web-inf文件下的方法 String path = Thread.currentThread().getContextClassLoader().getResource("mybaties-generator.xml").getPath(); //将给定的资源位置解析为File,即解析为文件系统中的文件 File file = ResourceUtils.getFile(path); ConfigurationParser configurationParser = new ConfigurationParser(warnings); Configuration config = configurationParser.parseConfiguration(file); DefaultShellCallback callback = new DefaultShellCallback(overwrite); MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); myBatisGenerator.generate(null); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (XMLParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidConfigurationException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
- 需要在application.properties中配置,不然无法找到mapper.xml文件
#需要配置,不然会包BindingException异常,找不到mapper.xml文件 mybatis.mapper-locations=classpath:mapper/*.xml
- 实现向数据库添加数据
public abstract class UserService { public abstract int insert(User cord); } @Service @Transactional public class UserServiceImpl extends UserService { @Autowired private UserMapper userMapper; @Override public int insert(User cord) { return userMapper.insert(cord); } } @RestController public class UserController { @Autowired private UserService userService; //通过RequestBody实现与json交互 @RequestMapping(value = "/register", method = RequestMethod.POST) public String insert(@RequestBody User user) { int result = userService.insert(user); JSONObject jsonObject = JSONObject.fromObject(result); return jsonObject + ""; } }
- 报错DataSourceProperties$DataSourceBeanCreationException,在application.java启动类配上exclude
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); //closeSpringBootStartStyle(args); } }