1. 程式人生 > >1112_Springboot+Mybaits+Mysql資料庫增刪改查操作——上路

1112_Springboot+Mybaits+Mysql資料庫增刪改查操作——上路

Springboot+Mybaits+Mysql資料庫增刪改查操作

96

瘋人願的瘋言瘋語

2017.11.03 16:37* 字數 754 閱讀 414評論 0喜歡 4

最近在老師的建議下,參加了一個學習小組,主要了解Spring Cloud微服務架構的應用開發,在初次搭建好環境後,這一次使用Spring boot+Mybatis完成對資料庫的一些簡單操作,作為新手,下面就是我整個做的過程,查閱了許多網上的資料,這裡面很多都是學習別人的東西,自己說的也可能不專業,權當自己記錄複習。

1.任務要求

image.png

image.png

2.工程建立

springboot工程建立就不說了,這裡主要說一下pom.xml檔案新增的依賴,如下:

 
  1. <dependencies>

  2. <dependency>

  3. <groupId>org.springframework.boot</groupId>

  4. <artifactId>spring-boot-starter-web</artifactId>

  5. </dependency>

  6. <!--mybatis-->

  7. <dependency>

  8. <groupId>org.mybatis.spring.boot</groupId>

  9. <artifactId>mybatis-spring-boot-starter</artifactId>

  10. <version>1.3.1</version>

  11. </dependency>

  12.  
  13. <!--pagehelper-->

  14. <dependency>

  15. <groupId>com.github.pagehelper</groupId>

  16. <artifactId>pagehelper-spring-boot-starter</artifactId>

  17. <version>1.2.1</version>

  18. </dependency>

  19.  
  20. <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->

  21. <dependency>

  22. <groupId>org.projectlombok</groupId>

  23. <artifactId>lombok</artifactId>

  24. </dependency>

  25. </dependencies>

還有就是application.yml檔案的資料庫配置:

 
  1. spring:

  2. application:

  3. name: mysql-service

  4. datasource:

  5. driver-class-name: com.mysql.jdbc.Driver

  6. url: jdbc:mysql://localhost:3306/spring-c?useUnicode=true&characterEncoding=UTF-8

  7. username: root

  8. password: hui19970201

3.應用檔案建立及說明

新建一個應用,目錄結構如下:

 

image.png

entity層

(1)根據要求在entity層建立User實體類,內容如下:

 
  1. @Getter

  2. @Setter

  3. public class User {

  4. private String userId;

  5.  
  6. private String userCode;

  7.  
  8. @Max(value = 100, message = "年齡不能大於100歲")

  9. @Min(value = 18, message = "必須年滿18歲!")

  10. private int age;

  11.  
  12. @Pattern(regexp = "[a-za-z0-9._%+-][email protected][a-za-z0-9.-]+\\.[a-za-z]{2,4}", message = "郵件格式錯誤")

  13. private String mail;

  14.  
  15. @Length(min = 11, max = 11, message = "手機號長度必須為11位")

  16. private String phone;

  17.  
  18. private int groupId;

  19. private Date createTime;

  20. private String createBy;

  21. private Date modifiedTime;

  22. private String modifiedBy;

  23. }

(2)根據要求在entity層建立JsonResult實體類,內容如下:

 
  1. @Data

  2. public class JsonResult {

  3.  
  4. private Long total;

  5. private String message;

  6. private boolean status;

  7. private Object data;

  8.  
  9. public JsonResult(String message, boolean status) {

  10.  
  11. this.message = message;

  12. this.status = status;

  13. }

  14.  
  15. public JsonResult(Long total, String message, boolean status) {

  16. this.total = total;

  17. this.message = message;

  18. this.status = status;

  19. }

  20.  
  21. public JsonResult(String message, boolean status, Object data) {

  22. this.message = message;

  23. this.status = status;

  24. this.data = data;

  25. }

  26.  
  27. public JsonResult(Long total, String message, boolean status, Object data) {

  28. this.total = total;

  29. this.message = message;

  30. this.status = status;

  31. this.data = data;

  32. }

  33. }

(3)一些解釋
首先是用來lombok的註解@Data,@Getter,@Setter減少了程式碼了,就不用那麼多的get和set方法了,當然你也可以使用IDE的generate來生成,隨自己喜好就行,如果使用的是IDEA,這裡注意引入依賴之後還需要下載lombok的外掛,重啟就能生效了;然後就是用Validator,主要是校驗使用者提交的資料的合理性,這裡大家可以百度一下具體的用法,下面是一些常見的註解及實際用法(複製別人的):

 
  1. @null 驗證物件是否為空

  2. @notnull 驗證物件是否為非空

  3. @asserttrue 驗證 boolean 物件是否為 true

  4. @assertfalse 驗證 boolean 物件是否為 false

  5. @min 驗證 number 和 string 物件是否大等於指定的值

  6. @max 驗證 number 和 string 物件是否小等於指定的值

  7. @decimalmin 驗證 number 和 string 物件是否大等於指定的值,小數存在精度

  8. @decimalmax 驗證 number 和 string 物件是否小等於指定的值,小數存在精度

  9. @size 驗證物件(array,collection,map,string)長度是否在給定的範圍之內

  10. @digits 驗證 number 和 string 的構成是否合法

  11. @past 驗證 date 和 calendar 物件是否在當前時間之前

  12. @future 驗證 date 和 calendar 物件是否在當前時間之後

  13. @pattern 驗證 string 物件是否符合正則表示式的規則

  14. @Email 驗證郵箱

  15.  
  16. 實際例子:

  17. @size (min=3, max=20, message="使用者名稱長度只能在3-20之間")

  18. @size (min=6, max=20, message="密碼長度只能在6-20之間")

  19. @pattern (regexp="[a-za-z0-9._%+-][email protected][a-za-z0-9.-]+\\.[a-za-z]{2,4}", message="郵件格式錯誤")

  20. @Length(min = 5, max = 20, message = "使用者名稱長度必須位於5到20之間")

  21. @Email(message = "比如輸入正確的郵箱")

  22. @NotNull(message = "使用者名稱稱不能為空")

  23. @Max(value = 100, message = "年齡不能大於100歲")

  24. @Min(value= 18 ,message= "必須年滿18歲!" )

  25. @AssertTrue(message = "bln4 must is true")

  26. @AssertFalse(message = "blnf must is falase")

  27. @DecimalMax(value="100",message="decim最大值是100")

  28. DecimalMin(value="100",message="decim最小值是100")

  29. @NotNull(message = "身份證不能為空")

  30. @Pattern(regexp="^(\\d{18,18}|\\d{15,15}|(\\d{17,17}[x|X]))$", message="身份證格式錯誤")

dao層

程式碼如下:

 
  1. @Mapper//這裡的Mapper是Mybatis自己定義的註解。

  2. public interface UserDao {

  3. //插入資料

  4. @Insert("insert into user(userId,userCode,age,mail,phone,groupId," +

  5. "createTime,createBy,modifiedTime,modifiedBy)" +

  6. "values (#{userId,jdbcType=VARCHAR}, #{userCode,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}," +

  7. "#{mail,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, #{groupId,jdbcType=INTEGER}," +

  8. "#{createTime,jdbcType=TIMESTAMP}, #{createBy,jdbcType=VARCHAR}, #{modifiedTime,jdbcType=TIMESTAMP}," +

  9. "#{modifiedBy,jdbcType=VARCHAR})")

  10. void insertUser(User user);

  11. //更新資料

  12. @Update("update user set userId=#{userId,jdbcType=VARCHAR}," +

  13. " userCode=#{userCode,jdbcType=VARCHAR}," +

  14. " age=#{age,jdbcType=INTEGER}," +

  15. " mail=#{mail,jdbcType=VARCHAR}," +

  16. " phone=#{phone,jdbcType=VARCHAR}," +

  17. " groupId=#{groupId,jdbcType=INTEGER}," +

  18. " createTime=#{createTime,jdbcType=TIMESTAMP}," +

  19. " createBy=#{createBy,jdbcType=VARCHAR}," +

  20. " modifiedTime=#{modifiedTime,jdbcType=TIMESTAMP}," +

  21. " modifiedBy=#{modifiedBy,jdbcType=VARCHAR} where userId=#{userId,jdbcType=VARCHAR}")

  22. void updateUser(User user);

  23.  
  24. //根據userId刪除一個使用者的資料

  25. @Delete("delete from user where useId = #{useId,jdbcType=VARCHAR}")

  26. void deletdUserById(String userId);

  27. //根據userCode刪除一個使用者的資料

  28. @Delete("delete from user where userCode = #{userCode,jdbcType=VARCHAR}")

  29. void deletdUserByCode(String userCode);

  30. //根據userCode取出一個使用者的資料

  31.  
  32. @Select("select * from user WHERE userCode = #{userCode,jdbcType=VARCHAR}")

  33. User getUserByCode(String userCode);

  34. //根據userId取出一個使用者的資料

  35. @Select("select * from user WHERE userId = #{userId,jdbcType=VARCHAR}")

  36. User getUserById(String userId);

  37. @Select("select userCode,age,phone,modifiedTime from user ORDER BY modifiedTime DESC")

  38. List<User> getUserList();

  39.  
  40. }

這裡使用mybatis註解的方式@Insert、@Update、@Delete、@Select來進行資料庫的資料庫操作,當然也可使用Mapper對映檔案,我個人覺得簡單的sql操作使用註解,麻煩的還是使用Mapper檔案比較好。這裡推薦幾篇文章。
MyBatis 3(中文版) 第四章 使用註解配置SQL對映器
Mybatis中Mapper對映檔案詳解

service層

程式碼如下:

 
  1. @Service

  2. public class UserServices {

  3. @Autowired

  4. private UserDao userDao;

  5.  
  6. public JsonResult add(User user){

  7. User User= userDao.getUserByCode(user.getUserCode());

  8. if(User!=null){

  9. return new JsonResult("userCode已存在",false);

  10. }

  11. user.setUserId(UUID.randomUUID().toString());

  12. user.setCreateTime(new Date());

  13. user.setModifiedTime(new Date());

  14. userDao.insertUser(user);

  15. return new JsonResult("success",true);

  16. }

  17.  
  18. public JsonResult delete(String userId,String userCode){

  19. User User=null;

  20. if(userId==null&&userCode==null){

  21. return new JsonResult("缺少引數userId或userCode",false);

  22. }else if(userId==null){

  23. User= userDao.getUserByCode(userCode);

  24. if(User==null){

  25. return new JsonResult("userCode不存在,無法刪除",false);

  26. }

  27. userDao.deletdUserByCode(userCode);

  28. }else {

  29. User= userDao.getUserById(userId);

  30. if(User==null){

  31. return new JsonResult("userId不存在,無法刪除",false);

  32. }

  33. userDao.deletdUserById(userId);

  34. }

  35.  
  36. return new JsonResult("success",true);

  37. }

  38.  
  39. public JsonResult update(User user){

  40. User User= userDao.getUserById(user.getUserId());

  41. if(User==null){

  42. return new JsonResult("沒有此userId",false);

  43. }

  44.  
  45. user.setModifiedTime(new Date());

  46. userDao.updateUser(user);

  47. return new JsonResult("success",true);

  48. }

  49.  
  50. public JsonResult detail(String userId, String userCode){

  51. User User=null;

  52. if(userId==null){

  53. User= userDao.getUserByCode(userCode);

  54. }else if(userCode==null){

  55. User= userDao.getUserById(userId);

  56. }

  57. System.out.println(User);

  58. return new JsonResult("success",true,User);

  59. }

  60.  
  61. public JsonResult list(int pageNum,int pageSize){

  62. PageHelper.startPage(pageNum, pageSize);

  63. List<User> list= userDao.getUserList();

  64. //把list包裝成PageInfo物件才能序列化,該外掛也預設實現了一個PageInfo

  65. PageInfo<User> pageInfo = new PageInfo<User>(list);

  66. //得到總的資料條數

  67. Long total=pageInfo.getTotal();

  68. return new JsonResult(total,"success",true,list);

  69. }

  70. }

這裡主要看一下list()方法,這裡採用了pagehelper外掛,pageNum為頁面頁數,pageSize為一頁資料的數量,需要把把list包裝成PageInfo物件才能序列化,使用getTotal()方法得到資料的條數。pagehelper外掛的的依賴引入如下,一直遇到報空錯誤,更新一下版本就好了。
Spring Boot+Mybatis+Pagehelper分頁

controller層

程式碼如下:

 
  1. @RestController //使用這個方法代表rest風格的控制器

  2. public class UserController {

  3.  
  4. @Autowired

  5. private UserServices userServices; //注入服務方法;

  6.  
  7. @RequestMapping(value = "/add", method= RequestMethod.POST)

  8. public Object add(@Valid @RequestBody User user, BindingResult result){

  9. if(result.hasErrors()){

  10. String msg="";

  11. List<FieldError> fieldErrors=result.getFieldErrors();

  12. for (FieldError fieldError:fieldErrors){

  13. msg+=fieldError.getDefaultMessage()+",";

  14. }

  15. return new JsonResult(msg.substring(0,msg.length()-1),false);

  16. }

  17. return userServices.add(user);

  18. }

  19.  
  20. @RequestMapping(value = "/delete",method= RequestMethod.POST)

  21. public Object delete(String userId,String userCode){

  22. return userServices.delete(userId,userCode);

  23. }

  24.  
  25. @RequestMapping(value = "/update",method= RequestMethod.POST)

  26. public Object update(@RequestBody User user){

  27. return userServices.update(user);

  28. }

  29.  
  30. @RequestMapping(value = "/detail",method= RequestMethod.GET)

  31. public Object detail(String userId,String userCode){

  32. return userServices.detail(userId,userCode);

  33. }

  34.  
  35. @RequestMapping(value = "/list",method= RequestMethod.GET)

  36. public Object list(){

  37. int pageNum=1;

  38. int pageSize=5;

  39. return userServices.list(pageNum,pageSize);

  40. }

  41. }

這裡的@RequestBody代表引數的傳入得是json格式,Validator註解@Valid說明需要檢查的物件,如果有錯誤,錯誤結果都會傳入BindingResult,裡面就是具體的用法了。
59. Spring Boot Validator校驗【從零開始學Spring Boot】

程式入口

 
  1. @SpringBootApplication()

  2. public class mysqlApplication {

  3. public static void main(String[] args){

  4. SpringApplication.run(mysqlApplication.class,args);

  5. }

  6. }

  7.  

4.測試

測試採用google瀏覽器的postman外掛來發送get/post請求,部分結果如下:

add

add_failed

add_success

detail

detail_get

 

detail_result

list

list
 

 

 

------------------------------------

Mapper

-----------------------------------

@Mapper
public interface DemoMapper {

    //增
    @Insert("INSERT INTO demo(name,age)VALUES(#{name},#{age})")
    @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //獲取插入後自動生成的主鍵,keyProperty對應類屬性名,keyColumn對應資料庫欄位名
    int add(Demo demo);

    //刪
    @Delete("DELETE FROM demo WHERE id=#{id}")
    boolean deleteById(int id);

    //查
    @Select("SELECT * FROM demo WHERE id=#{id}")
    Demo findById(int id);
    @Select("SELECT * FROM demo WHERE login=#{login} AND password=#{password}")
    Demo findByObject(@Param("login") String login,@Param("password") String password);

    //改,注意:需要指定引數對映@Param,如不指定,可按下面的方法執行
    @Update("UPDATE demo SET name=#{name} WHERE id =#{id}")
    boolean updateById(@Param("name") String name,@Param("id") int id);
    @Update("UPDATE demo SET name=#{name} WHERE id =#{id}")
    boolean update_2ById(Demo demo);


    //批量增
    @InsertProvider(type = LoginProvider.class,method = "insert")
    int insert(@Param("demoList")List<Demo> demoList);

    //批量刪
    @DeleteProvider(type = LoginProvider.class,method = "delete")
    boolean delete(@Param("demoList")List<Demo> demoList);

    //批量查
    @Select("SELECT * FROM demo")
    List<Demo> find();
    @SelectProvider(type = LoginProvider.class,method = "find2")
    List<Demo>find2(@Param("demoList")List<Demo> demoList);


    //批量改
    @UpdateProvider(type = LoginProvider.class,method = "update")
    boolean update(@Param("demoList")List<Demo> demoList);


}