Mybatis series (1) -- JSP + Spring + Mybatis + Mysql framework construction
Xiaobian is also busy learning java. After reading the introduction of Mybatis during meals and before going to bed, I learned how to practice it, and the learning time is not long, I created a framework in two days and shared it with you.
MyBatis is an excellent persistent layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual settings of almost all JDBC code and parameters and retrieves the result set. MyBatis uses simple XML or annotations for configuration and original ing. It maps interfaces and Java POJOs (Plain Old Java Objects, a common Java object) into records in the database. I learned Hibernate before, and recently took the time to learn about Mybatis. I made a simple comparison between them.
[Simple comparison between Hibernate and Mybatis]
1. Differences in query statements.
Previously developed with Hibernate, all of them use encapsulated statements, and there is no SQL shadow at all. They are all called methods. However, Mybatis is a good choice for some slightly complex SQL statements. Therefore, in terms of query efficiency, we recommend that you use Hibernate to encapsulate simple queries, which can save a lot of time. If you do not recommend that all fields be returned .. Complex SQL statements may be used for large projects. It is easy to adjust Mybatis manual writing and you can see what you are writing. It is a good choice.
2. From the perspective of object management mechanism.
Hibernate is a complete object/link ing. It provides object State management, so that developers no longer need to care about the details of the underlying database system. In this way, the object-oriented method persists the data to the database, regardless of fields in the database. Hibernate can also write SQL statements to specify the fields to be queried, but this compromises the simplicity of Hibernate development. Mybatis SQL is manually written, so you can specify the query fields as needed.
ResultMap is the most powerful element in MyBatis. You can save 90% of the Code by calling the result set using JDBC. It also allows you to do a lot of things that are not supported by JDBC. In fact, it is necessary to write a complex statement that is equivalent to a ing similar to interaction. It may require thousands of lines of code. The purpose of ResultMap is to make such a simple statement without unnecessary result ing.
3. cache mechanism.
Hibernate provides two levels of Cache. The first level of Cache is Session-level Cache, which belongs to the scope of transactions. This level of cache is managed by hibernate and generally requires no intervention. The second level of cache is the SessionFactory level cache, which belongs to the process scope or cluster scope. This level of cache can be configured and changed, and can be dynamically loaded and detached. It belongs to multiple transaction levels and must prevent transaction concurrency. The cache is stored in the form of map (key-id, value-object ).
In Mybatis, a level-1 cache is a local HashMap cache based on PerpetualCache (which comes with mybatis). The scope of the cache is session. Therefore, when session commit or close, the cache is cleared. The second-level cache is also based on PerpetualCache by default, but you can set a storage source for it. The first-level cache caches SQL statements, while the second-level cache caches result objects.
Hibernate's second-level cache configuration is detailed in the configuration file generated by SessionFactory, and then configured in the specific table-object ing as the cache. The second-level cache configuration of MyBatis is configured in detail in each specific table-object ing, so that different cache mechanisms can be customized for different tables.
[JSP + Spring + Mybatis + Mysql framework setup]
1. Create a web project and introduce the required jar packages, spring, mybatis, and mysql.
2. web. xml configuration
MyBatis_Spring3_Jsp
index.jsp
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
contextConfigLocation
classpath*:config/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
org.springframework.web.context.ContextCleanupListener
mvc-dispatcher
org.springframework.web.servlet.DispatcherServlet
1
mvc-dispatcher
/
3. mvc-dispatcher-servlet.xml file configuration
/WEB-INF/pages/
.jsp
4. spring applicationContext. XML file configuration
5. Add the configuration file configuration. xml of Mybatis.
5. Compile the controller class and model class.
UserController class:
package com.yihaomen.controller;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.yihaomen.inter.IUserOperation;import com.yihaomen.model.Article;import com.yihaomen.model.User;@Controller@RequestMapping("/article")public class UserController { @Autowired IUserOperation userMapper; @RequestMapping("/list") public ModelAndView listall(HttpServletRequest request,HttpServletResponse response){ List articles=userMapper.getUserArticles(1); ModelAndView mav=new ModelAndView("list"); mav.addObject("articles",articles); return mav;}}
Interface Class:
package com.yihaomen.inter;import java.util.List;import com.yihaomen.model.Article;import com.yihaomen.model.User;public interface IUserOperation { public User selectUserByID(int id);public List
selectUsers(String userName);public void addUser(User user);public void updateUser(User user);public void deleteUser(int id);public List getUserArticles(int id);}
User. xml (SQL is written here)
Select user. id, user. userName, user. userAddress, article. id aid, article. title, article. content from user, article where user. id = article. userid and user. id = # {id}
Model class:
package com.yihaomen.model;public class Article {private int id;private User user;private String title;private String content;public int getId() {return id;}public void setId(int id) {this.id = id;}public User getUser() {return user;}public void setUser(User user) {this.user = user;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}}
6. JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
test
${item.id }--${item.title }--${item.content }
Running effect:
[Summary]
1) Each MyBatis application mainly uses SqlSessionFactory instances. A SqlSessionFactory instance can be obtained through SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can be obtained from an xml configuration file or an instance of a predefined configuration class. Creating a SqlSessionFactory instance using an xml file is very simple.
2) read more books and do it first. This is a profound understanding. One day, I will be familiar with it and have time issues.