javascript
Springboot Mybatis 整合(完整版)
前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
正題
本項目使用的環境:
開發工具:Intellij IDEA 2017.1.3
springboot: 1.5.6
jdk:1.8.0_161
maven:3.3.9
額外功能
PageHelper 分頁插件
mybatis generator 自動生成代碼插件
步驟:
1.創建一個springboot項目:
2.創建項目的文件結構以及jdk的版本
3.選擇項目所需要的依賴
然后點擊finish
5.看一下文件的結構:
6.查看一下pom.xml:
7.項目不使用application.properties文件 而使用更加簡潔的application.yml文件:
將原有的resource文件夾下的application.properties文件刪除,創建一個新的application.yml配置文件,
文件的內容如下:
8.創建數據庫:
CREATE DATABASE mytest;CREATE TABLE t_user(user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,user_name VARCHAR(255) NOT NULL ,password VARCHAR(255) NOT NULL ,phone VARCHAR(255) NOT NULL ) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;9.使用mybatis generator 自動生成代碼:
配置pom.xml中generator 插件所對應的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration><!-- 數據庫驅動:選擇你的本地硬盤上面的數據庫驅動包--><classPathEntry ?location="E:\developer\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/><context id="DB2Tables" ?targetRuntime="MyBatis3"><commentGenerator><property name="suppressDate" value="true"/><!-- 是否去除自動生成的注釋 true:是 : false:否 --><property name="suppressAllComments" value="true"/></commentGenerator><!--數據庫鏈接URL,用戶名、密碼 --><jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root"></jdbcConnection><javaTypeResolver><property name="forceBigDecimals" value="false"/></javaTypeResolver><!-- 生成模型的包名和位置--><javaModelGenerator targetPackage="com.winter.model" targetProject="src/main/java"><property name="enableSubPackages" value="true"/><property name="trimStrings" value="true"/></javaModelGenerator><!-- 生成映射文件的包名和位置--><sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources"><property name="enableSubPackages" value="true"/></sqlMapGenerator><!-- 生成DAO的包名和位置--><javaClientGenerator type="XMLMAPPER" targetPackage="com.winter.mapper" targetProject="src/main/java"><property name="enableSubPackages" value="true"/></javaClientGenerator><!-- 要生成的表 tableName是數據庫中的表名或視圖名 domainObjectName是實體類名--><table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table></context> </generatorConfiguration>點擊run-Edit Configurations
添加配置
運行
注意!!!同一張表一定不要運行多次,因為 mapper 的映射文件中會生成多次的代碼,導致報錯,切記
最后生成的文件以及結構:
10. 生成的文件
UserMapper.javapackage com.winter.mapper;import com.winter.model.User;public interface UserMapper {int deleteByPrimaryKey(Integer userId);int insert(User record);int insertSelective(User record);User selectByPrimaryKey(Integer userId);int updateByPrimaryKeySelective(User record);int updateByPrimaryKey(User record);//這個方式我自己加的List<User> selectAllUser(); }User.java
package com.winter.model;public class User {private Integer userId;private String userName;private String password;private String phone;public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName == null ? null : userName.trim();}public String getPassword() {return password;}public void setPassword(String password) {this.password = password == null ? null : password.trim();}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone == null ? null : phone.trim();} }對于 sql 語句這種黃色的背景,真心是看不下去了(解決方案):
**UserMapper.xml?? ?**
11.打開類 SpringbootMybatisDemoApplication.java,這個是 springboot 的啟動類。我們需要添加點東西:
package com.winter;import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication @MapperScan("com.winter.mapper")//將項目中對應的mapper類的路徑加進來就可以了 public class SpringbootMybatisDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisDemoApplication.class, args);} }注意:@MapperScan("com.winter.mapper") 這個注解非常的關鍵,這個對應了項目中 mapper(dao)所對應的包路徑,很多同學就是這里忘了加導致異常的
12.到這里所有的搭建工作都完成了,接下來就是測試的工作,沒使用 junit4 進行測試:
首先看一下完成之后的文件的結構:
現在controller,service層的代碼都寫好:
UserController.java
package com.winter.Controller;import com.winter.model.User; import com.winter.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;/*** Created by Administrator on 2017/8/16.*/ @Controller @RequestMapping(value = "/user") public class UserController {@Autowiredprivate UserService userService;@ResponseBody@RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})public int addUser(User user){return userService.addUser(user);}@ResponseBody@RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){return userService.findAllUser(pageNum,pageSize);} }UserService.java
package com.winter.service;import com.winter.model.User;import java.util.List;/*** Created by Administrator on 2017/8/16.*/ public interface UserService {int addUser(User user);List<User> findAllUser(int pageNum, int pageSize); }UserServiceImpl.java
package com.winter.service.impl;import com.github.pagehelper.PageHelper; import com.winter.mapper.UserMapper; import com.winter.model.User; import com.winter.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import java.util.List;/*** Created by Administrator on 2017/8/16.*/ @Service(value = "userService") public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;//這里會報錯,但是并不會影響@Overridepublic int addUser(User user) {return userMapper.insertSelective(user);}/** 這個方法中用到了我們開頭配置依賴的分頁插件pagehelper* 很簡單,只需要在service層傳入參數,然后將參數傳遞給一個插件的一個靜態方法即可;* pageNum 開始頁數* pageSize 每頁顯示的數據條數* */@Overridepublic List<User> findAllUser(int pageNum, int pageSize) {//將參數傳給這個方法就可以實現物理分頁了,非常簡單。PageHelper.startPage(pageNum, pageSize);return userMapper.selectAllUser();} }如果強迫癥看不下去那個報錯:(解決方法)
測試我使用了 idea 一個很用心的功能。
可以發 http 請求的插件:
點擊左側的運行按鈕就可以發送請求了;
如果返回值正確 說明你已經搭建成功了!
如果出現mapper注入不了的情況,請檢查版本.
轉自:https://blog.csdn.net/winter_chen001/article/details/77249029?
?
總結
以上是生活随笔為你收集整理的Springboot Mybatis 整合(完整版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++:json字符串拼接,json对象
- 下一篇: C/C++由字符串转JSON/JSON转