Primitive development mode
Implementation process
- Write SqlMapConfig.xml configuration file and mapper.xml configuration file
Database Profile<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--Loading configuration files--> <properties resource="db.properties"></properties> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${db.driver}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
UserMapper.xmldb.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/ssm db.username=root db.password=admin
When you use like above, you use $instead of #, as for the difference between $and #. The difference between $and #<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN " "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace The purpose is to classify and manage the mapping files MapperdStatement object--> <mapper namespace="test"> <select id="findUserById" parameterType="int" resultType="test.User"> select * from User where id = #{hello} </select> <!--${value}Indicates that the input parameter will ${value}Replacement, do string splicing directly. If you take a simple number of parameters, the parameter name in parentheses must be value--> <select id="findUserByUsername" parameterType="java.lang.String" resultType="test.User"> select * from user where username like '%${value}%' </select> <insert id="insertUser" parameterType="test.User"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> select LAST_INSERT_ID() </selectKey> insert into user(username, birthday, sex, address) values (#{username}, #{birthday}, #{sex}, #{address}) </insert> </mapper>
- Development Interface (DAO Layer Interface)
package top.dao; import test.User; public interface UserDao { User findUserById(int id) throws Exception; void insertUser(User user) throws Exception; }
- Implementing interfaces (DAO implementation classes, which deal with databases through sqlsesion)
package top.dao.impl; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import test.User; import top.dao.UserDao; public class UserDaoImpl implements UserDao { private SqlSessionFactory sqlSessionFactory; // Injecting sqlsessionFactory public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } @Override public User findUserById(int id) throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.findUserById", id); sqlSession.close(); return user; } @Override public void insertUser(User user) throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); sqlSession.insert("test.insertUser", user); sqlSession.commit(); sqlSession.close(); } }
- Test class
@Test public void testFindById() throws Exception { UserDao userDao = new UserDaoImpl(sqlSessionFactory); User user = userDao.findUserById(1); System.out.println(user); }
Life Cycle of Several Objects
-
sqlSession: Method Level
The so-called method level is the object that needs to be created within the method.
-
SqlSession Factory: Global scope, application level
-
sqlSessionFactoryBuilder: Method Level
mapper agent development (xml configuration file)
Mapper agent development method is to use interface development method. When the original Dao is used for development, not only the Dao interface is established, but also the implementation class of dao. We build sqlsession object in the implementation class to operate the database. Now the so-called mapper agent development method is to remove the implementation class of dao. It only needs to keep the interface, but there are preconditions for using mapper proxy to develop it. Specific conditions are as follows:
- The class path of the mapper interface needs to be the same as the namespace in the mapper.xml file It's important to note that the class path is not the package path. If the package path is written, the following error will occur. org.apache.ibatis.binding.BindingException: Type interface top.mapper.UserMapper is not known to the MapperRegistry.
- The method name of the mapper interface needs to be the same as the id of each state defined in mapper.xml
- The method input parameter type of the mapper interface needs to be the same as the type of parameterType for each sql defined in mapper.xml
- The output parameter type of the method of the mapper interface is the same as the resultType of each sql defined in mapper.xml The above cases are still amended:
mapper file
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN " "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace The purpose is to classify and manage the mapping files MapperdStatement object--> <mapper namespace="top.mapper.UserMapper"> <select id="findUserById" parameterType="int" resultType="test.User"> select * from User where id = #{hello} </select> <!--${value}Indicates that the input parameter will ${value}Replacement, do string splicing directly. If you take a simple number of parameters, the parameter name in parentheses must be value--> <select id="findUserByUsername" parameterType="java.lang.String" resultType="test.User"> select * from user where username like '%${value}%' </select> <insert id="insertUser" parameterType="test.User"> <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer"> select LAST_INSERT_ID() </selectKey> insert into user(username, birthday, sex, address) values (#{username}, #{birthday}, #{sex}, #{address}) </insert> </mapper>
Here you can see that the namespace in the mapper file has been changed, which is the class path of the mapper interface.
mapper interface
package top.mapper; import test.User; public interface UserMapper { User findUserById(int id) throws Exception; void insertUser(User user) throws Exception; }
Test code
package test; 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.Before; import org.junit.Test; import top.mapper.UserMapper; import top.mapper.impl.UserMapperImpl; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; public class TestUser { // Conversation Factory private SqlSessionFactory sqlSessionFactory; // This annotation can be executed before the @test annotation @Before public void createSqlSessionFactory() throws IOException { // Loading configuration files String resource = "SqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // Create sqlsessionfactory from xml using sqlSession FactoryBuilder sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testMapperFind() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); // Get the proxy object of the mapper interface UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // Calling proxy object methods User user = userMapper.findUserById(1); System.out.println(user); sqlSession.close(); } }
Common labels for SqlMapperConfig.xml configuration files
The main configuration file of mybatis can configure the label as follows:
- Properties (attributes, you can load external properties files in. For example, the database configuration file)
-
<! - Load configuration file - > <properties resource= "db. properties"> </properties>
-
In addition to using the resource attribute, you can use the property subtag defined in the properties tag to define the data attributable value.
<properties> <property name="driver" value="com.mysql.jdbc.Driver"/> </properties>
-
mybatis first reads the attributes in the properties element, then reads the attributes loaded by the url or resource, and then overrides the attributes with the same name that have been read.
-
- settings (global configuration parameters)
- TypeeAlias tag, defining aliases
- Batch or single definition alias
<typeAliases> <! - Define an alias - >. <!--<typeAlias type="test.User" alias="user"/>--> <! - Define aliases in batches. Scan the entire package for the class under the alias name (size or lowercase can be used)--> <package name="test"/> </typeAliases>
- Batch or single definition alias
- mappers tag
- <mapper resource="/> (single)
- Use resources relative to class paths
- Case: <mapper resource="sqlmap/User.xml"/>
- <mapper class="/> (single)
- The interface class path is used
- Case: <mapper class="com.kkb.mybatis.mapper.UserMapper"/>
- At this point, it is important to note that the mapper interface name is the same as the mapper mapping file name and should be placed in the same directory.
- <package name="/> (batch)
- Register all mapper interfaces under the specified package to load the mapping file
- Case: <package name="com.kkb.mybatis.mapper"/>
- In batch mode, the name of mapper interface is required to be the same as that of mapper mapping file and placed in the same directory.
- <mapper resource="/> (single)