Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction of mybatis and Environment Construction

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

First, the reasons for not using pure jdbc, that is, disadvantages.

1. The database understands that creating when in use and releasing when not in use will frequently open and close links to the database, resulting in a waste of database resources and affecting the performance of the database.

Imagine: use the connection pool of the database.

2. Hard-coding sql statements into java code is not conducive to system maintenance.

Imagine: put sql in the configuration file.

3. Setting parameters to preparedstatement, placeholder position and setting parameter values are hard-coded in Java code, which is not conducive to system maintenance.

Imagine: configure sql statements and placeholders into xml.

4. When the result set is convenient from resultset, there is hard coding, and the fields obtained from the table are hard-coded, which is not conducive to system maintenance.

Imagine that the result set is automatically mapped to a Java object

What is mybatis?

1. Mybatis allows programmers to focus on sql and generate sql statements that meet their needs freely and flexibly through the mapping provided by mybatis.

2. Mybatis can automatically map input parameters and map the result set to Java objects, and sql is relatively free, unlike hibernate without seeing sql.

3. Mybatis needs a SqlMapConfig.xml, which is the global configuration file of mybatis, including database connection pool, configured data source, transaction, and so on.

4, also need a SQLMap configuration file, which configures the mapping relationship (configure sql statements), sql statements to be written in this configuration file, in fact, is to configure a statement, to avoid sql statements hard-coded into the Java source file. The use of this configuration file will be described in more detail later.

5. SqlsessionFactory is the factory that generates Sqlsession in mybatis and operates the database.

The mybatis framework structure loads the mapping file of sql statements into SQLMapConfig, and then SqlSessionFactory loads SQLMapConfig and generates SQLSession,SQLSession to execute Statement.

Third, build a mybatis project.

1. Required jar package

That is, you need to download the mybatis package and the database driver package. You can download mybatis from GitHub. After decompression, there is a lib folder and a core package of mybatis. The package in lib is a dependent package of mybatis.

Download mybatis

two。 Engineering structure.

Put the source code in src, the dependent jar package in lib, various configuration files in config, and the sql mapping file in the sqlmap package under the config file. Remember to select build path- > use a source folder after the lib and config folders are created

3. Write log4j.properties

# Global logging configurationlog4j.rootLogger=DEBUG, stdout# MyBatis logging configuration...log4j.logger.org.mybatis.example.BlogMapper=TRACE# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [% t] -% m% n

Note: when developing log4j.rootLogger=DEBUG, the production environment can replace DEBUG with info.

4. Write SqlMapConfig.xml

The sql mapping file for each object is included, and the data source is configured in the environment tag, and there are only two places that need to be changed.

5. Write user.xml

Select * from users where id=# {id} select * from users where name like'% ${value}% 'insert into users (name,birthday,address,sex) values (# {name}, # {birthday}, # {address}, # {sex}) select last_insert_id () delete from users where id=# {id} update users set name=# {name} Address=# {address}, birthday=# {birthday}, sex=# {sex} where id=# {id}

Here, a total of four sql statements for query, insert, delete and update are written, all wrapped in corresponding tags. Each tag will eventually be mapped to a statement. The attribute id in the tag is the only indication of this statement. Later, it will be called through this id in Java. ParameterType represents input parameters, similar to the type of parameters that are assigned to placeholders during precompilation of jdbc.

ResultType is the type of pojo class that the database returns the result.

The tag is used to return the primary key. When you insert a record, add this tag to the id that immediately gets the record, where the keyProperty attribute indicates the primary key attribute of the entity class, order indicates whether the query is executed before or after insertion, and resultType is the result type of the query.

6. Create an entity class corresponding to the database, because it is relatively simple, the code is no longer given here

7. Use Junit to test.

Package mt;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.List;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 org.junit.Test;import entity.Classes;import entity.users;public class FirstDemo {@ Test public void findUserbyIdTest () {try {String resource= "SqlMapConfig.xml" InputStream stream=Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder (). Build (stream); SqlSession sqlSession=sqlSessionFactory.openSession (); users u=sqlSession.selectOne ("test.srarchByid", 1); System.out.println (u.getBirthday (). ToString ()); sqlSession.close () } catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} @ Test public void findUserByName () {try {String resource= "SqlMapConfig.xml"; InputStream stream=Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder () .build (stream); SqlSession sqlSession=sqlSessionFactory.openSession () List u=sqlSession.selectList ("test.searchByName", "Zhang"); sqlSession.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} @ Test public void insertUser () {try {String resource= "SqlMapConfig.xml" InputStream stream=Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder (). Build (stream); SqlSession sqlSession=sqlSessionFactory.openSession (); users u=new users (); u.setName ("Wang Lei"); u.setSex ("f"); u.setBirthday (new Date ()); u.setAddress ("Shanghai") SqlSession.insert ("test.insertUser", u); System.out.println (u.getId ()); sqlSession.commit (); sqlSession.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace () } @ Test public void deleteUser () {try {String resource= "SqlMapConfig.xml"; InputStream stream=Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder () .build (stream); SqlSession sqlSession=sqlSessionFactory.openSession (); sqlSession.insert ("test.deleteUser", 2); sqlSession.commit (); sqlSession.close () } catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} @ Test public void updateUser () {try {String resource= "SqlMapConfig.xml"; InputStream stream=Resources.getResourceAsStream (resource); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder () .build (stream); SqlSession sqlSession=sqlSessionFactory.openSession (); users u=new users () U.setId (3); u.setName ("Wang Lei"); u.setSex ("f"); u.setBirthday (new Date ()); u.setAddress ("Shanghai 66666"); sqlSession.update ("updateUser", u); System.out.println (u.getId ()); sqlSession.commit () SqlSession.close ();} catch (IOException e) {/ / TODO Auto-generated catch block e.printStackTrace ();}

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.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report