- 在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); } }