In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to get started with Mybatis". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to get started with Mybatis.
The main contents of this paper are as follows:
Traditional JDBC
Traditional JDBC coding format
Public class DataBaseUtil {public static final String URL = "jdbc:mysql://localhost:3306/mblog"; public static final String USER = "root"; public static final String PASSWORD = "123456"; public static void main (String [] args) throws Exception {Class.forName ("com.mysql.jdbc.Driver"); / / 2. Connection conn = DriverManager.getConnection (URL, USER, PASSWORD) / 3. Statement stmt = conn.createStatement (); / / 4. ResultSet rs = stmt.executeQuery ("SELECT id, name, age FROM m_user where id = 1") / / if data is available, rs.next () returns true while (rs.next ()) {System.out.println ("name:" + rs.getString ("name") + "age:" + rs.getInt ("age"));}
The knowledge in the above code is to show the whole process of JDBC (exceptions and resources are simple and rough handling, we do not focus on these two points).
It can be divided into six steps:
Load driver
Get a database connection
Create a Statement object
Operate the database to add, delete, modify and check
Get the result set
Close the resource
In terms of use, the cost of using the original JDBC in the project is still very high. If the business in our project is relatively complex, there are relatively many database tables, and there will be more ways to add, delete, modify and query the database, then the code will be repeated a lot.
The problems of traditional JDBC
There is a lot of hard coding in the connection to create the database.
Hard coding exists when executing statement.
Frequently opening and closing database connections will seriously affect the performance of the database and waste database resources.
There is a lot of repetitive coding.
In order to solve the above problems, a variety of products to replace JDBC have been born. That is, the ORM framework.
What is ORM?
Its full name is Object Relational Mapping. Object-mapping-relational database. Object-relational mapping (ORM, or O/RM, or Omax R mapping) is used to convert data between different types of systems in object-oriented programming languages. To put it simply, ORM maps objects in a program to a relational database by using metadata that describes the mapping between objects and databases.
ORM provides another mode to implement the persistence layer, which uses mapping metadata to describe the mapping of object relations, so that ORM middleware can act as a bridge between the business logic layer and the database layer of any application.
Our project goes like this:
For example: Apache DbUtils, Spring JDBC, Hibernate, Ibatis (the previous life of Mybatis), Spring Data Jpa and so on.
At present, the most popular Mybatis and Spring Data Jpa. We'll talk about Mybatis,Jpa later in this series.
Advantages and disadvantages of ORM
Advantages 1. The development efficiency is improved. Because ORM can automatically map fields and attributes between Entity objects and Table in the database, we may no longer need a dedicated, huge data access layer. 2.ORM provides mapping to the database, does not need sql direct coding, and can obtain data from the database like an Operand object.
Disadvantages sacrifice the execution efficiency of the program and will fix the mode of thinking, reducing the flexibility of development.
From the point of view of the system structure, the system using ORM is generally a multi-tier system. If there are more levels of the system, the efficiency will be reduced. ORM is a complete object-oriented approach, and the object-oriented approach can also have an impact on performance. When we develop a system, we usually have performance problems. Performance problems are mainly caused by incorrect algorithms and incorrect use of the database. The code generated by ORM is generally unlikely to write a very efficient algorithm, and it is more likely to be misused in database applications, mainly reflected in the extraction of persistent objects and data processing. If you use ORM, programmers are likely to extract all the data to memory objects, and then filter and process them, so it is easy to produce performance problems. When you persist an object, ORM generally persists all of its properties, which is sometimes undesirable. But ORM is a tool, and tools do solve some repetitive, simple tasks. This is undeniable. But we can't expect tools to solve all the problems once and for all. Some problems still need special treatment, but the parts that need special treatment should be very few for most systems.
What is MyBatis?
If asked during the interview, as long as you name the following three.
MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping.
MyBatis eliminates almost all the JDBC code and the work of setting parameters and getting result sets.
MyBatis can configure and map primitive types, interfaces, and Java POJO (Plain Old Java Objects, plain old Java objects) to records in the database through simple XML or annotations.
From the official website.
Advantages and disadvantages of MyBatis
Advantages:
(1) programming based on SQL statements, quite flexible, will not cause any impact on the existing design of the application or database, SQL is written in XML, uncoupling sql and program code, facilitate unified management; provide XML tags, support for the preparation of dynamic SQL statements, and can be reused.
(2) compared with JDBC, it reduces the amount of code by more than 50%, eliminates a lot of redundant code in JDBC, and does not need to switch and connect manually.
(3) good compatibility with various databases (because MyBatis uses JDBC to connect to the database, so as long as the database MyBatis supported by JDBC supports it).
(4) be able to integrate with Spring
(5) provide mapping label to support ORM field mapping between object and database, and provide object-relational mapping label to support the maintenance of object-relational components.
Shortcoming
The main results are as follows: (1) there is a large amount of work to write SQL statements, especially when there are many fields and associated tables, there are certain requirements for developers to write SQL statements.
(2) the SQL statement depends on the database, which leads to the poor portability of the database, so the database can not be replaced at will.
Construction of Mybatis Environment and simple examples
Create a database table
Create a m_user table using the MySQL database.
CREATE TABLE `muser` (`id` int (11) NOT NULL AUTO_INCREMENT, `name` varchar (255) DEFAULT NULL, `age` int (11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
Add dependency
Org.mybatis mybatis 3.5.2 mysql mysql-connector-java 8.0.16 runtime
The project structure is as follows:
Create a mybatis-config.xml
Entity class User
Ublic class User {private Integer id; private String name; private Integer age; / / set get @ Override public String toString () {return "User {" + "id=" + id + ", name='" + name +'\'+ ", age=" + age +'}';}}
Create UserMapper.java
Import com.tian.mybatis.entity.User; public interface UserMapper {User selectUserById (Integer id);}
Create UserMapper.xml
Select * from m_user where id = # {id}
Create a test class
Import com.tian.mybatis.entity.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class MybatisApplication {public static void main (String [] args) {String resource = "mybatis-config.xml"; InputStream inputStream = null; SqlSession sqlSession = null Try {inputStream = Resources.getResourceAsStream (resource); / / Factory mode SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream); / / sql operation session sqlSession = sqlSessionFactory.openSession (); / / get data and parse into User object User user = sqlSession.selectOne ("com.tian.mybatis.mapper.UserMapper.selectUserById", 1) System.out.println (user);} catch (Exception e) {e.printStackTrace ();} finally {try {inputStream.close ();} catch (IOException e) {e.printStackTrace ();} sqlSession.close ();}
Output result:
User {id=1, name='tian', age=22}
Overall steps:
Another way to start up
Import com.tian.mybatis.entity.User; import org.apache.ibatis.builder.xml.XMLConfigBuilder; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory; import java.io.IOException; import java.io.InputStream; import java.util.Properties Public class MybatisApplication {public static void main (String [] args) {String resource = "mybatis-config.xml"; InputStream inputStream = null; try {inputStream = Resources.getResourceAsStream (resource);} catch (IOException e) {e.printStackTrace ();} / parse xml file XMLConfigBuilder parser = new XMLConfigBuilder (inputStream, null, null) / / build a SqlSessionFactory factory class SqlSessionFactory sqlSessionFactory = build (parser.parse ()); / / create a SqlSession SqlSession sqlSession = sqlSessionFactory.openSession (); / / get the data and parse it into a User object User user = sqlSession.selectOne ("com.tian.mybatis.mapper.UserMapper.selectUserById", 1); System.out.println (user) } public static SqlSessionFactory build (Configuration config) {return new DefaultSqlSessionFactory (config);}}
The output is the same as above. You can also use Java code directly instead of mybatis-config.xml.
/ / create data source DataSource dataSource = getDataSource (); TransactionFactory transactionFactory = new JdbcTransactionFactory (); Environment environment = new Environment ("development", transactionFactory, dataSource); Configuration configuration = new Configuration (environment); configuration.addMapper (BlogMapper.class); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (configuration)
Small summary
From the above case, we can roughly guess that the most important components of Mybatis are:
SqlSessionFactoryBuilder
SqlSessionFactory
SqlSession
Mapper
The SqlSessionFactoryBuilder class can be initialized, used, and discarded, and if you have already created a SqlSessionFactory, you don't have to keep it. Therefore, the best scope for SqlSessionFactoryBuilder is in the method body, such as defining a method variable.
You can reuse SqlSessionFactoryBuilder to generate multiple SqlSessionFactory instances, but it's best not to force it, because XML's parsing resources are used for other more important things.
Once SqlSessionFactory is created, SqlSessionFactory will always exist throughout the application process. So there is no reason to destroy and recreate it, and it is not recommended to create a SqlSessionFactory multiple times when an application is running. If you do that, it will look very clumsy.
So the best scope for SqlSessionFactory is Application. There are many ways to do this. The easiest way is singleton mode or static singleton mode. However, this is not widely approved and useful. Instead, it is better to use Google Guice or Spring for dependency reflection. These frameworks allow you to generate a manager to manage the singleton life cycle of SqlSessionFactory
SqlSession each thread has its own SqlSession instance, and SqlSession instances cannot be shared and are not thread-safe. Therefore, it is best to use Request scope or method body scope.
Do not use a static variable of a class to refer to an instance of SqlSession, or even an instance change of a class. Never reference SqlSession in a managed domain, such as in HttpSession in Servlet. If you are using the WEB framework, you should let SqlSession follow the similar scope of HTTP requests.
That is, after receiving a HTTP request, open SqlSession and turn off the SqlSession as soon as a response is returned. It is very important to turn off SqlSession. You have to make sure that SqlSession closes properly in the body of the finally method.
SqlSession session = sqlSessionFactory.openSession (); try {/ / do work} finally {session.close ();}
Use this pattern to run through all your code to ensure that all database resources are completely closed.
Mapper
Mapper is an interface you create for binding mapping statements. The instance of the Mapper interface is obtained using SqlSession. Similarly, technically, the broadest Mapper instance scope, like SqlSession, uses the request scope. Specifically, the Mapper instance is called when the method is called, and then automatically destroyed when it is used. There is no need for an explicit logout. When a request is executed correctly, like SqlSession, you can easily manipulate it. Keep it simple and keep Mapper within the scope of the method body.
/ / get the data and parse it into a User object User user = sqlSession.selectOne ("com.tian.mybatis.mapper.UserMapper.selectUserById", 1); System.out.println (user)
Here the mapping involves four principals:
Entity class User.
Interface UaerMapper.
Xml profile UserMapper.
Database table m_user
Mybatis's five songs:
Thank you for your reading, the above is the content of "how to get started with Mybatis". After the study of this article, I believe you have a deeper understanding of how to get started with Mybatis, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.