Making the source address: https://github.com/mybatis/mybatis-3
What is Mybatis
MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. It can configure and map SQL information using simple XML or annotations, Map the interface and Java’s POJOs(Plain Old Java Objects) to records in the database.
The origin of Mybatis
MyBatis is an open source project of Apache called iBatis.
In 2010 the project was migrated from Apache Software Foundation to Google Code and renamed MyBatis.
Migrated to Github in November 2013.
What is the ORM
OBJECT/RELATIONALMAPPING (ORM) is produced with the development of object-oriented software development method. Used to map objects represented by the object model to sqL-based relational model database structures. In this way, we do not need to deal with complex SQL statements in the specific operation of entity objects, but simply operate the attributes and methods of entity objects. ORM technology provides a bridge between objects and relationships, through which object data in the foreground and relational data in the database can be transformed into each other.
Difference between ORM framework and MyBatis
Compare the item
Mybatis
Hibernate
Market share
high
high
Suitable industry
Internet e-commerce project
Traditional (ERP, CRM, OA)
performance
high
low
Sql flexibility
high
low
To study the threshold
low
high
Sql configuration file
Global configuration files, mapping files
Global configuration files, mapping files
ORM
semi-automatic
Full automation
Database independence
low
high
Encoding process
Write the global configuration file: xxxconfig.xml
POJO class
Mapping file: xxxmapper.xml
Write DAO code: xxxDao interface, xxxDaoImpl implementation class
Unit test class
demand
1. Query information about a user based on the user ID
2. Query the user information list based on the user name
<! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mappernamespace="test"> </mapper> Copy the code
PO class
publicclassUser{
privateint id; private String username; private Date birthday; private String sex; private String address; / / the getter \ setter methods } Copy the code
Need to implement
Query the user
The mapping file
<! Get user information by id --> <selectid="findUserById"parameterType="int"resultType="com.kkb.mybatis.po.User"> select * from user where id = #{id} </select>
<! -- Query user list by name --> <selectid="findUserByUsername"parameterType="java.lang.String" resultType="com.kkb.mybatis.po.User"> select * from user where username like '%${value}%' </select> Copy the code
Configuration description:
- parameterType: defines the Java types of input parameters. - resultType: defines the result mapping type. - #{} : equivalent to JDBC? A placeholder - #{id} means to use preparedStatement to set the placeholder symbol and pass the input variable ID to SQL. - ${value} : Fetch the parameter namevalueThe value of the. The ${value} placeholder substitution.
Note: If you are taking a parameter of simple quantity type, the parameter name in parentheses must bevalue Copy the code
Dao interfaces and implementation classes
publicinterfaceUserDao{ public User findUserById(int id)throws Exception; public List<User> findUsersByName(String name)throws Exception; } Copy the code
Life cycle (scope of action)
Sqlsession: method level
SqlsessionFactory: Global scope (application level)
@Override public User findUserById(int id)throws Exception { SqlSession session = sqlSessionFactory.openSession(); User user = null; try { // Call the selectOne method from sqlSession to get a result set Parameter 1: specifies the ID of the statement to be defined. Parameter 2: specifies the parameter to be passed to statement user = session.selectOne("test.findUserById", id); System.out.println(user); } finally{ session.close(); } return user; }
@Test publicvoidtestFindUserById(a){ UserDao userDao = new UserDaoImpl(sqlSessionFactory); User user = userDao.findUserById(22); System.out.println(user); } @Test publicvoidtestFindUsersByName(a){ UserDao userDao = new UserDaoImpl(sqlSessionFactory); List<User> users = userDao.findUsersByName("Guo"); System.out.println(users); } } Copy the code
#{} and ${}
The difference between 1
#{} : equivalent to placeholders in JDBC SQL statements? (PreparedStatement)
The ${}: corresponds to a connection in a JDBC SQL Statement that matches + (Statement). Copy the code
The difference between two
#{} : Input mapping is performed to parse the parameter (if the parameter is String, then the SQL statement automatically adds' ').
The ${}: During input mapping, parameters are output to the SQL statement as is Copy the code
The difference between 3
#{} : If the input mapping is for simple types (String, Date, 8 basic wrapper classes),The parameter names in #{} can be arbitrary ${} : If the input mapping is for simple types (String, Date, 8 basic wrapper classes),The ${}The parameter name must be value Copy the code
The difference between 4
The ${}: SQL injection problems exist. The keyword OR 1=1 is used to ignore query conditions Copy the code
Add user
#{} : StaticSqlSource is used to fetch data via reflection
${} : the OGNL expression changes hierarchically as the object is nested
The mapping file
<! Add user --> <insertid="insertUser"parameterType="com.kkb.mybatis.po.User"> insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}) </insert> Copy the code
Dao interfaces and implementation classes
publicinterfaceUserDao{ publicvoidinsertUser(User user)throws Exception; } Copy the code
<insertid="insertUser"parameterType="com.kkb.mybatis.po.User"> <! -- selectKey returns primary key, needs to return --> <selectKeykeyProperty="id"order="AFTER"resultType="java.lang.Integer"> select 1608976 </selectKey> insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}); </insert> Copy the code
Add the selectKey tag for primary key return.
KeyProperty: Specifies the returned primary key, which property is stored in the POJO
The order in which SQL is executed in the ORDER: selectKey tag, as opposed to the INSERT statement. Selectkeys are executed in after order because of mysql’s increment principle that primary keys are generated after the insert statement.
ResultType: Indicates the JAVA type of the returned primary key
1608976: is a mysql function that returns the id of a new auto_increment column.
This series of articles has been included in the Github Backend advancement Guide. The project is under development. Welcome star.
The articles in the public account are the original bloggers, and will always be updated. If you want to witness or grow with bloggers, welcome to follow!