In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you the example analysis of the addition, deletion, modification and core configuration of the Mybatis framework in Java. I hope you will gain something after reading this article. Let's discuss it together.
Original JDBC operation
Original jdbc operation (query data)
Original jdbc operation (insert data)
Analysis of the original jdbc operation the problems with the original jdbc development are as follows:
The frequent creation and release of ① database connections results in a waste of system resources and affects system performance.
The ② sql statement is hard-coded in the code, which makes the code difficult to maintain. The actual application of sql may change greatly, and the change of sql needs to change the java code.
During the ③ query operation, you need to manually encapsulate the data in the result set into the entity. When inserting, you need to manually set the data of the entity to the placeholder position of the sql statement
Solutions to the above problems:
① uses database connection pooling to initialize connection resources
② extracts sql statements into the xml configuration file
③ uses underlying technologies such as reflection and introspection to automatically map attributes and fields between entities and tables.
Introduction to Mybatis
① mybatis is an excellent persistence layer framework based on java, which encapsulates jdbc internally, so that developers only need to pay attention to the sql statement itself, without having to deal with complicated processes such as loading drivers, creating connections, creating statement, and so on.
② mybatis configures all kinds of statement to be executed by xml or annotation, and maps the java object to the dynamic parameters of sql in statement to generate the final executed sql statement.
③ finally the mybatis framework executes sql and maps the result to a java object and returns. The idea of ORM is adopted to solve the problem of mapping between entity and database, jdbc is encapsulated, and the underlying access details of jdbc api are shielded, so that we can complete the persistence operation of the database without dealing with jdbc api.
Mybatis official website address: mybatis-MyBatis 3 | Introduction
Mybatis development steps:
① add the coordinates of MyBatis
② creates user data sheet
Writing User entity classes with ③
④ compiles the mapping file UserMapper.xml
⑤ compiles the core file SqlMapConfig.xml
⑥ writes test classes
① adds coordinates of MyBatis and other related coordinates
Mysql mysql-connector-java 5.1.32 org.mybatis mybatis 3.4.6 junit junit 4.12 log4j log4j 1.2.17
② creates user data sheet
Writing User entity classes with ③
Public class User {private int id; private String username; private String password; / / omit get and set methods}
④ compiles the mapping file UserMapper.xml
Select * from user
⑤ compiles Mybatis core file SqlMapConfig.xml
⑥ writes test classes
@ Test / / query operation public void test1 () throws IOException {/ / get the core configuration file InputStream resourceAsStream = Resources.getResourceAsStream ("sqlMapConfig.xml"); / / get the session factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (resourceAsStream); / / get the session reply object SqlSession sqlSession = sqlSessionFactory.openSession () / / execute operation parameters: namespace+id List userList = sqlSession.selectList ("userMapper.findAll"); / / print data System.out.println (userList); / / release resource sqlSession.close ();} Overview of Mybatis mapping file
The operation of adding, deleting, changing and searching Mybatis
Insert data operation of ① Mybatis
Write UserMapper mapping file
Insert into user values (# {id}, # {username}, # {password})
Write User code to insert entities
@ Test / / insert operation public void test2 () throws IOException {/ / simulate user object User user = new User (); user.setUsername ("xxx"); user.setPassword ("abc"); / / get the core configuration file InputStream resourceAsStream = Resources.getResourceAsStream ("sqlMapConfig.xml") / / get session factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (resourceAsStream); / / get session reply object SqlSession sqlSession = sqlSessionFactory.openSession (true); / / execute operation parameters: namespace+id sqlSession.insert ("userMapper.save", user); / / release resource sqlSession.close ();}
Note on the insertion operation:
Insert statements using insert tags
Use the parameterType attribute in the mapping file to specify the data type to insert
Use # {entity attribute name} in the Sql statement to refer to the attribute value in the entity
The API used by the insert operation is sqlSession.insert ("namespace .id", entity object)
The insert operation involves changes in database data, so use the commit transaction displayed by the sqlSession object, that is, sqlSession.commit ()
Modify data operation of ② Mybatis
Write UserMapper mapping file
Update user set username=# {username}, password=# {password} where id=# {id}
Write User code that modifies the entity
@ Test / / modify operation public void test3 () throws IOException {/ / simulate user object User user = new User (); user.setId (7); user.setUsername ("lucy"); user.setPassword ("123"); / / get the core configuration file InputStream resourceAsStream = Resources.getResourceAsStream (" sqlMapConfig.xml ") / get session factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (resourceAsStream); / get session reply object SqlSession sqlSession = sqlSessionFactory.openSession (); / / execute operation parameters: namespace+id sqlSession.update ("userMapper.update", user); / / mybatis performs update operation to commit transaction because mybatis does not commit transaction sqlSession.commit () by default / / release resource sqlSession.close ();}
Note on the modification operation:
Modify statements using update tags
The API used by the modify operation is sqlSession.update ("Namespace .id", entity object)
Delete data operation of ③ Mybatis
Write UserMapper mapping file
Delete from user where id=# {abc}
Write User code to delete entities
@ Test / / delete operation public void test4 () throws IOException {/ / get the core configuration file InputStream resourceAsStream = Resources.getResourceAsStream ("sqlMapConfig.xml"); / / get the session factory object SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder () .build (resourceAsStream); / / get the session reply object SqlSession sqlSession = sqlSessionFactory.openSession () / / execute operation parameters: namespace+id sqlSession.delete ("userMapper.delete", 8); / / mybatis perform update operation to commit transaction sqlSession.commit (); / / release resource sqlSession.close ();}
Delete operation notes:
Delete statements use delete tags
Referencing a single parameter passed in a Sql statement using # {arbitrary string}
The API used by the delete operation is sqlSession.delete ("namespace .id", Object)
MyBatis Core profile Overview MyBatis Core profile hierarchy
Analysis of Common configuration of MyBatis
1.environments tag
Configuration of database environment to support multi-environment configuration
There are two types of transaction managers (transactionManager):
① JDBC: this configuration directly uses JDBC's commit and rollback settings, which rely on connections from the data source to manage the transaction scope.
② MANAGED: this configuration does little. It never commits or rolls back a connection, but instead lets the container manage the entire lifecycle of the transaction (such as the context of the JEE application server). By default it closes the connection, but some containers do not want this, so you need to set the closeConnection property to false to prevent its default closing behavior.
There are three types of data sources (dataSource):
① UNPOOLED: the implementation of this data source simply opens and closes the connection each time it is requested.
② POOLED: the implementation of this data source uses the concept of "pooling" to organize JDBC connection objects.
③ JNDI: this data source is implemented for use in containers such as EJB or application servers, which can configure the data source centrally or externally, and then place a reference to the JNDI context.
2.mapper tag
The function of this tag is to load the mapping, which can be loaded in the following ways:
① uses resource references relative to the classpath, for example:
② uses a fully qualified resource locator (URL), for example:
③ uses the mapper interface to implement the fully qualified class name, for example:
④ registers all mapper interface implementations within the package as mappers, for example:
3. Properties tag
4.typeAliases tag
Above we are custom aliases, and the mybatis framework has set up some common type aliases for us.
Mybatis corresponding API
① SqlSession Factory Builder SqlSessionFactoryBuilder
Common API: SqISessionFactory build (InputStream inputStream)
Build a SqlSessionFactory object by loading the input stream of the core file of mybatis
Among them, the Resources utility class, which is in the org.apache.ibatis.io package. The Resources class helps you load resource files from the classpath, the file system, or a web URL.
② SqlSession Factory object SqlSessionFactory
SqlSessionFactory has several ways to create SqlSession instances. Two commonly used ones are as follows:
③ SqlSession session object
The SqISession instance is a very powerful class in MyBatis. Here you will see all the methods for executing statements, committing or rolling back transactions, and getting mapper instances. The main ways to execute statements are:
The main ways to operate transactions are:
① void commit ()
② void rollback ()
After reading this article, I believe you have a certain understanding of "sample analysis of addition, deletion, modification and core configuration of Mybatis framework in Java". If you want to know more about it, welcome to follow the industry information channel, thank you for reading!
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.