MyBatis core profile
1.MyBatis core profile hierarchy
2.MyBatis common configuration analysis
(1) environment label
the configuration of database environment supports multi environment configuration
There are two types of transaction manager:
- JDBC: this configuration directly uses the commit and rollback settings of JDBC. It depends on the connection from the data source to manage the transaction scope
- MANAGED: this configuration does little. He never commits or rolls back a connection, but lets the container manage the whole life cycle of the transaction (such as the context of JEE application server). By default, it will close the connection, but some containers do not want this, so you need to set the closeConnection property to false to prevent it from closing by default.
There are three types of data sources:
- UNPOOLED: the implementation of this data source only opens and closes the connection every time it is requested
- POOLED: the implementation of this data source uses the concept of "pool" to organize JDBC connection objects
- JNDI: this data source is implemented to be used in containers such as EJB or application server. The container can centrally or externally configure the data eye, and then place a reference to the JNDI context
(2) mapper tag
this tag is used to load mapping. The loading methods are as follows:
- Use a resource reference relative to the classpath, for example: < mapper resource = "org/mybatis/builder/AuthorMapper.xml" / >
- Use a fully qualified resource locator (URL), for example: < mapper URL=“ fle://ar/mappers/AuthorMapper.xml ”/>
- Use the mapper interface to implement the fully qualified class name of the class, for example: < mapper class = "org.mybatis. builder.AuthorMapper" / >
- Register all the mapper interface implementations in the package as mappers, for example: < package name = "org.mybatis builder" / >
(3) Properties tag
in actual development, it is customary to extract the configuration information of the data source into a separate properties file, which can load additional configured properties files
Code example: //jdbc.properties.xml jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=123456
Code example: //sqlMapperConfig.xml <!--adopt properties Label load external properties file--> <properties resource="jdbc.properties"></properties> <!--Data source environment--> <environments default="developement"> <environment id="developement"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments>
Test screenshot:
(4) typeAliases label
The above are our customized aliases. mybaits framework has set some common types of aliases for us
alias | data type |
---|---|
string | String |
long | Long |
int | Integer |
double | Double |
boolean | Boolean |
... ... | ... ... |
Response API for MyBaits
1.SqlSession factory builder SqlSessionFactoryBuilder
common API: SqlSessionFactory build(InputStream inputStream)
Build a SqlSessionFactory object by loading the input stream of the core file of mybaits
String resource = "org/mybatis/builder/mybatis-congif.xml"; InputStream inputStream = Resource.getResourceAsStream(resource); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factor = builder.build(inputStream);
The Resources tool class is in the org.apache.ibatis.io package. The Resources class helps us load resource files from a path, file system, or a webURL
2.SqlSession factory object SqlSessionFactory
SqlSessionFactory has multiple methods to create SqlSession instances. There are two common methods:
3.SqlSession session object
SqlSession instance is a very powerful class in MyBaits. Here we will see all the methods for executing statements, committing or rolling back transactions, and getting mappers.
Dao layer implementation of MyBatis
1. Implementation of traditional Dao layer
Code example: //Dao interface public interface UserMapper { public List<User> findAll() throws IOException; }
Code example: //Dao implementation class public class UserMapperImpl implements UserMapper { @Override public List<User> findAll() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml");//Get configuration file through Resource SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);//Get factory object SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> userList = sqlSession.selectList("userMapper.findAll"); return userList; } }
Code example: //Test code public class ServiceDemo { public static void main(String[] args) throws IOException { //Create dao layer objects. The implementation of the current dao layer is written manually UserMapper userMapper = new UserMapperImpl(); List<User> all = userMapper.findAll(); System.out.println(all); } }
Test screenshot:
2. Agent development mode
(1) Introduction to agent development methods
adopt the agent development method of mybaits to realize the development of Dao layer, which is the mainstream of current enterprises. Mapper interface development method only requires programmers to write mapper interface (equivalent to Dao interface). Mybaits framework creates the dynamic proxy object of the interface according to the interface definition. The method body of the proxy object is the same as the implementation class method of Dao interface above.
Mapper interface development needs to follow the following specifications:
① the namespace in Mapper.xml file is the same as the fully qualified name of Mapper interface
② the Mapper interface method name is the same as the id of each statement defined in Mapper.xml
③ the input parameter type of Mapper interface method is the same as the parameterType of each sql defined in mapper.xml
④ the output type parameter of Mapper interface method is the same as the resultType of each sql defined in Mapper.xml
(2) Write UserMapper interface
(3) Test agent mode
Code example: //sqlMapperConfig.xml <!--Load mapping file--> <mappers> <package name="com.xc.dao"/> </mappers>
Code example: //sqlMapper.xml <mapper namespace="com.xc.dao.UserMapper"> <!--Query operation--> <select id="findAll" resultType="com.xc.domain.User"> select * from user </select> </mapper>
Code example: //ServiceDemo.java public class ServiceDemo { public static void main(String[] args) throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> all = mapper.findAll(); System.out.println(all); } }
Test screenshot:
Mapping file for MyBatis
1. Overview of mybatis mapping file
2. Dynamic sql statement
(1) Overview of dynamic sql statements
in the Mybaits mapping file, sometimes when the business logic is complex, SQL changes dynamically.
① dynamic SQL if
we use different SQL statements to query according to different values of entity classes. For example, if the id is not empty, you can query according to the id. if the username is different, you should add the username as a condition. This situation is often encountered in our multi condition combination query.
Code example: //UserMapper.xml <select id="findByCondition" parameterType="com.xc.domain.User" resultType="com.xc.domain.User"> select * from user where 1=1 <if test="id!=0"> and id=#{id} </if> <if test="username!=null"> and username=#{username} </if> <if test="password!=null"> and password=#{password} </if> </select>
Code example: //MapperTest.xml @Test public void test1() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //Simulation condition user User condition = new User(); condition.setId(1); condition.setUsername("Small A"); condition.setPassword("123"); List<User> userList = mapper.findByCondition(condition); System.out.println(userList); }
Test screenshot:
② dynamic SQL foreach
perform sql splicing operations circularly, for example: SELECT * FROM USER WHERE id IN(1,2,5)
Code example: //UserMapper.xml <select id="findByIds" parameterType="list" resultType="com.xc.domain.User"> select * from user <where> <foreach collection="list" open="id in(" close=")" item="id" separator=","> #{id} </foreach> </where> </select>
Code example: //MapperTest.xml @Test public void test2() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapperConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); //Simulate ids data List<Integer> ids = new ArrayList<>(); ids.add(1); ids.add(2); List<User> userList = mapper.findByIds(ids); System.out.println(userList); }
Test screenshot:
(2) SQL fragment extraction
duplicate SQL can be raised in SQL and referenced with include when used, so as to achieve the purpose of SQL reuse.
Code example: //UserMapper.xml <!--sql Extraction of statements--> <sql id="selectUser"> select * from user</sql>
3.MyBaits mapping file configuration summary