Java development learning experience (2): Mybatis and Url routing

Posted Jun 15, 20207 min read

The serial number is connected to the previous article Java development learning experience(1):SSM environment construction

1.3 Mybatis

MyBatis was originally an open source project iBatis of apache. In 2010, this project was migrated from apache software foundation to google code and renamed as MyBatis. MyBatis is a Java-based persistence layer framework. The persistence layer framework provided by iBATIS includes SQL Maps and Data Access Objects(DAO). MyBatis eliminates the manual setting of almost all JDBC codes and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, mapping interfaces and Java POJOs(Plain Old Java Objects, ordinary Java objects) to records in the database.

1.3.1 Differences from Hibernate

From a performance perspective

Since Hibernate has a higher degree of abstract encapsulation than MyBatis, in theory the performance of a single statement execution will be lower.

But Hibernate will set the cache, which has certain optimization for repeated queries, and in terms of coding efficiency, Hibernate's coding effect will definitely be higher. Therefore, from a holistic point of view, in fact, the two can't say who wins or who loses.

From the perspective of ORM

Hibernate is a complete ORM framework that conforms to the JPA specification, but MyBatis is not. MyBatis is definitely more convenient than writing JDBC, but it is inevitable to write SQL, and cross-database cannot be achieved. Hibernate can use JPA without worrying about database compatibility.

One difficulty with Hibernate is how to design the relationship between objects. If it is a relational database, tables and tables are related by foreign keys. In ORM, you need to design the relationship between objects from an object-oriented perspective. This requires a change in thinking.

in conclusion

Judging from the online discussions, emerging Internet companies use Mybatis more because of its easy-to-use features, and old large companies will continue to maintain their Hibernate projects.

1.3.2 Connect to the database

  1. Add dependencies

Add the dependency of MyBatis and the corresponding database in pom.xml

<!-- 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>

Note that the version number in the MySQL Version node must be consistent with the version of the MySQL driver you use. The high version around 8.0 is also different from the low version in the connection string setting, which will be explained below

After adding the dependency, IDEA will automatically import the corresponding package

  1. Create a class corresponding to the database table(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(){
     }

    }

Here, in addition to the corresponding properties, you must also add the get/set method to instantiate the object to get the value of the corresponding property. The shortcut key of IDEA is ALT+INSERT

  1. Three-tier structure and connection pool

The three-layer structure is shown in the figure. My understanding is 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;
      }

    }

There are two ways to write the connection string, but they are all in the application.properties file, but you can change the suffix of this file to .yml, which is 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

The function of the writing is the same. I didn t use the yml format, so I used someone else s picture. It should be noted that the string behind the url is the database connection problem mentioned above. The 5.x version is used normally. MySQL can directly use this ordinary connection string, but I didn't know it at the beginning. Using the latest 8.x version, direct connection to the database will report an error. Like the writing in application.properties, the value will be passed by get later. With a series of explanations, the specific role has not been studied in depth

2 URL routing

The class marked by @Controller represents a controller that processes HTTP requests(that is, C in MVC). All methods marked by @RequestMapping in this class will be used to process requests for the corresponding URL.

2.1 @RequestMapping

In the Spring MVC framework, use the @RequestMapping annotation to bind the URL to the processing method. Take a look at the controller example above

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

Use @Controller to mark the DemoController class, and @RequestMapping to mark the methods inside. When the application is running, visit http://localhost :8080/in the browser, and the request will be Spring MVC The framework is distributed to the index() method for processing. Similarly, http://localhost :8080/user will be handed over to the getUser() method.

2.2 @PathVariable

What if you need to pass parameters? The {} in the route is the parameter. Accessing with http://localhost :8080/user/1 will pass 1 as the input parameter, id, into the method getUser(), http://127.0.0.1 :8080/username/AAA The same is true

2.3 Different request types

There are four commonly used HTTP methods in Web applications:

  • Resources added by the PUT method
  • The GET method is used to obtain existing resources
  • POST method is used to change the state of resources
  • DELETE method is used to delete existing resources

These four methods can correspond to CRUD operations(Create, Read, Update, and Delete). Each Web request belongs to one of them. If not specified in Spring MVC, the default is a GET request.

In fact, @RequestMapping("/") is shorthand for @RequestMapping("/", method = RequestMethod.GET), that is, you can set the HTTP method of the request through the method attribute.

For example, PUT /hello request, corresponding to @RequestMapping("/hello", method = RequestMethod.PUT)

The latest version of Spring MVC provides a more concise way to configure the HTTP method, adding four annotations:

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

2.4 @ResponseBody

With this annotation added, the return value will be displayed directly on the browser, which is roughly Response.Write() in .NET. If an entity is returned here, it will be displayed in json format. If you want to display the page, you need to Return the corresponding HTML format code, but this is not conducive to browsing and maintenance, so you need to route to an HTML page

Tips

  1. Auto-save:IDEA is automatically saved. Every time you type, you will have a save operation. At the beginning, you will also get used to Ctrl+S, but you will get used to it slowly. If you need a new reference, just enter it. Yes, IDEA will automatically quote, just like adding dependencies
  2. Case-sensitivity:IDEA itself is very strict with case-sensitivity. If you start with a capital S, there will be no prompt starting with a lower-case s in the automatic prompt. Unlike C#, Java types usually start with uppercase