1. 程式人生 > >Java開發學習心得(二):Mybatis和Url路由

Java開發學習心得(二):Mybatis和Url路由

rac 處理 2.4 報錯 localhost insert 實體 tips control

Java開發學習心得(二):Mybatis和Url路由

序號接上一篇Java開發學習心得(一):SSM環境搭建

1.3 Mybatis

MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名為MyBatis 。MyBatis是一個基於Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了幾乎所有的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始映射,將接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。

1.3.1 和Hibernate的區別

從性能角度考慮

由於 Hibernate 比 MyBatis 抽象封裝的程度更高,理論上單個語句執行的性能會低一點。

但 Hibernate 會設置緩存,對於重復查詢有一定的優化,而且從編碼效率來說,Hibernate 的編碼效果肯定是會高一點的。所以,從整體的角度來看性能的話,其實兩者不能完全說誰勝誰劣。

從ORM角度考慮

Hibernate 是完備的 ORM 框架,是符合 JPA 規範的,但 MyBatis 不是。MyBatis 比單純寫 JDBC 肯定是方便一點,但無可避免還是要寫SQL,且無法做到跨數據庫 。Hibernate 使用 JPA 就可以無需考慮數據庫的兼容性問題。

使用 Hibernate 的一個難點是,如何來設計對象之間的關系。如果是關系型數據庫的話,表和表是通過外鍵來進行關聯的。而在 ORM 中,則需要從面向對象的角度出發,來設計對象之間的關聯關系。這個是需要思路上做一個轉變的。

結論

從網上的討論來看,新興互聯網公司更多地使用Mybatis,是因為其易於上手的特性,而舊的大型公司仍然會繼續維護他們的Hibernate項目。

1.3.2 連接數據庫

  1. 添加依賴

在pom.xml中添加MyBatis與相應數據庫的依賴

<!-- MyBatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.13</version>
</dependency>

註意MySQL的Version節點中的版本號要與你使用的MySQL驅動的版本一致,8.0左右的高版本在連接串設置上也與低版本不同,會在下文說明

添加依賴之後,IDEA會自動導入相應的包

  1. 建立與數據庫表對應的類(javabean)
package com.example.dataObject;

public class User {
    private Long id;
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User(){
    }
}

這裏除了相應的屬性,還要添加get/set方法,實例化的對象才能獲取相應屬性的值,IDEA的快捷鍵是ALT+INSERT

  1. 三層結構及連接池

三層的結構如圖,我的理解是Mapper→Service→Controller

技術分享圖片

  • Mapper
package com.example.dataMapper;

import com.example.dataObject.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM USER WHERE NAME = #{name}")
    User findByName(@Param("name") String name);

    @Select("SELECT * FROM USER WHERE ID = #{id}")
    User getById(@Param("id") Long id);

    @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name,@Param("age") Integer age);
}
  • Service
package com.example.service;

import com.example.dataMapper.UserMapper;
import com.example.dataObject.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;

    public User findUser(Long id){
        User user = userMapper.getById(id);
        return  user;
    }

    public User findUserByName(String name){
        User user = userMapper.findByName(name);
        return  user;
    }
}
  • Controller
package com.example;

import com.example.dataObject.User;
import com.example.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;

@Controller
public class DemoController {
    @Autowired
    UserService userService;

    @RequestMapping("/")
    @ResponseBody
    public String index(){
        return "Hello Spring Boot";
    }

    @RequestMapping("/user/{id}")
    @ResponseBody
    public String getUser(@PathVariable("id") Long id){
        User user = userService.findUser(id);
        return user.getName();
    }

    @RequestMapping("/username/{name}")
    @ResponseBody
    public User getUserByName(@PathVariable("name") String name){
        User user = userService.findUserByName(name);
        return user;
    }
}

連接串有兩種寫法,但是其實都是在application.properties這個文件裏,但是可以把這個文件的後綴改為.yml使用,這樣就是application.yml

  • application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=limingxu
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  • application.yml

技術分享圖片

寫法的作用是一樣的,我沒用使用yml格式的,所以找了用了別人的圖,要註意的是url後面的那一串,這就是前面說的數據庫連接問題,正常使用5.x版本的MySQL可以直接使用這種普通的連接串,但是我一開始不知道,用了最新的8.x版本,直接連接數據庫會報錯,要像application.properties裏面的寫法在後面通過get傳值的方式加上一串說明,具體作用還沒有深入研究

2 URL路由

@Controller標註的類表示是一個處理HTTP請求的控制器(即MVC中的C),該類中所有被@RequestMapping標註的方法都會用來處理對應URL的請求。

2.1 @RequestMapping

在Spring MVC框架中,使用@RequestMapping標註可以將URL與處理方法綁定起來,看一下上面的控制器例子

package com.example;

import com.example.dataObject.User;
import com.example.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;

@Controller
public class DemoController {
    @Autowired
    UserService userService;

    @RequestMapping("/")
    @ResponseBody
    public String index(){
        return "Hello Spring Boot";
    }

    @RequestMapping("/user/{id}")
    @ResponseBody
    public String getUser(@PathVariable("id") Long id){
        User user = userService.findUser(id);
        return user.getName();
    }

    @RequestMapping("/username/{name}")
    @ResponseBody
    public User getUserByName(@PathVariable("name") String name){
        User user = userService.findUserByName(name);
        return user;
    }
}

用@Controller標註DemoController類,用@RequestMapping分別標註裏面的方法,當應用程序運行後,在瀏覽器中訪問http://localhost:8080/,請求會被Spring MVC框架分發到index()方法進行處理。同理,http://localhost:8080/user會交給getUser()方法進行處理。

2.2 @PathVariable

如果需要傳參數呢?路由中的{}就是參數,以http://localhost:8080/user/1 訪問就會將1作為入參即id傳入方法getUser(),http://127.0.0.1:8080/username/AAA 同理

2.3 不同的請求類型

在Web應用中常用的HTTP方法有四種:

  • PUT方法用來添加的資源
  • GET方法用來獲取已有的資源
  • POST方法用來對資源進行狀態轉換
  • DELETE方法用來刪除已有的資源

這四個方法可以對應到CRUD操作(Create、Read、Update和Delete),每一個Web請求都是屬於其中一種,在Spring MVC中如果不特殊指定的話,默認是GET請求。

實際上@RequestMapping("/")@RequestMapping("/", method = RequestMethod.GET)的簡寫,即可以通過method屬性,設置請求的HTTP方法。

比如PUT /hello請求,對應@RequestMapping("/hello", method = RequestMethod.PUT)

Spring MVC最新的版本中提供了一種更加簡潔的配置HTTP方法的方式,增加了四個標註:

  • @PutMapping
  • @GetMapping
  • @PostMapping
  • @DeleteMapping

2.4 @ResponseBody

加了這個標註,返回值會被直接顯示在瀏覽器上,大致就是.NET裏面的Response.Write(),如果在這裏返回一個實體,會以json的格式顯示,要想顯示頁面,這裏就要返回相應的HTML格式的代碼,但是這樣寫不利於瀏覽與維護,所以就需要路由到一個HTML的頁面

Tips

  1. 自動保存:IDEA裏面是自動保存的,你每一次輸入都會有保存操作,一開始還會習慣性Ctrl+S,但慢慢就習慣了,如果有需要新的引用,也只要輸入就可以,IDEA會自動引用,和添加依賴一樣
  2. 區分大小寫:IDEA本身對大小寫的區分很嚴格,如果你用大寫S開頭,自動提示裏面就不會出現小寫s開頭的提示。與C#不同,Java的類型通常是以大寫開頭

Java開發學習心得(二):Mybatis和Url路由