Get the App
SLTechnology News&Howtos  ›  Database  › 

Mybatis Learning Notes, introduction and Quick start

Shulou Source: shulou.com Published: 2022-06-01 13:06:46 10月27日 Update

What is 1.MyBatis?

MyBatis is an excellent persistence layer framework that supports normal SQL queries, stored procedures, and high-level mapping. MyBatis eliminates almost all manual setting of JDBC code and parameters and retrieval encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and raw mapping, mapping interfaces and Java's POJO (Plain Old Java Objects, plain Java objects) to records in the database. MyBatis allows programmers to focus on sql, through the mapping provided by MyBatis, free and flexible generation (semi-automatic, mostly requires programmers to write sql) to meet the needs of sql statements.

The frame structure of 2.MyBatis

Configuration file for 3.MyBatis

4. Mapping file

SELECT * FROM USER WHERE id=# {value} SELECT * FROM USER WHERE username LIKE'% ${value}% 'SELECT LAST_INSERT_ID () insert into user (username,birthday,sex,address) value (# {username}, # {birthday}, # {sex}, # {address}) delete from user where id=# {id} update user set username=# {username}, birthday=# {birthday}, sex=# {sex}, address=# {address} where id=# {id}

The properties of the pojo object are:

/ / the attribute name corresponds to the field of the database table

Private int id

Private String username;// user name

Private String sex;// gender

Private Date birthday;// 's birthday

Private String address;// address

/ / and the get,set method of the attribute

5. Usage

/ / mybatis configuration file String resource = "SqlMapConfig.xml"; / / get the profile flow InputStream inputStream = Resources.getResourceAsStream (resource); / / create a session factory and pass in the profile information of mybatis SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder (). Build (inputStream); / / get SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession () through the factory / / manipulate the database through SqlSession / / the first parameter: map the id of statement in the file, equal to = namespace+ "." + the second parameter of id// of statement: specify the parameter of parameterType type matched in the mapping file / / sqlSession.selectOne result is an object of type resultType matching in the mapping file / / selectOne query a record User user = sqlSession.selectOne ("test.findUserById", 1); System.out.println (user) / / release resource sqlSession.close ()

Tags: Files configurations parameters objects properties data databases normal factories methods frameworks programs programmers types results queries excellent original advanced free Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Docker Shulou Information NVidia Apple