mybatis basic information


Preface

Remember the basic information of mybatis


1. Mybatis tradition and agency development

Write UserDao interface

public interface UserDao {
    
    
	List<User> findAll() throws IOException;
} 

Write UserDaoImpl implementation

public class UserDaoImpl implements UserDao {
    
    
	public List<User> findAll() throws IOException {
    
    
	InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	List<User> userList = sqlSession.selectList("userMapper.findAll");
	sqlSession.close();
	return userList;
	}
}

Testing the traditional way

@Test
public void testTraditionDao() throws IOException {
    
    
	UserDao userDao = new UserDaoImpl();
	List<User> all = userDao.findAll();
	System.out.println(all); 
}

Agent development method: The
mybatis framework creates dynamic agent objects of the interface according to the definition of interface m, and the method body of the agent object is the same as that of the Dao interface implementation class method above.
Mapper interface development needs to follow the following specifications:
1. The namespace in the Mapper.xml file is the same as the fully qualified name of the mapper interface 2. The
Mapper interface method name is the same as the id of each statement defined in
Mapper.xml 3. The input of the Mapper interface method The parameter type is the same as the parameterType of each SQL defined in
mapper.xml 4. The output parameter type of the Mapper interface method is the same as the resultType of each SQL defined in the mapper.xml
Insert picture description here
Test proxy mode

@Test
public void testProxyDao() throws IOException {
    
    
	InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
	SqlSession sqlSession = sqlSessionFactory.openSession();
	//获得MyBatis框架⽣成的UserMapper接⼝的实现类
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	User user = userMapper.findById(1);
	System.out.println(user);
	sqlSession.close();
}

Two, Mybatis configuration file

1. The core configuration file SqlMapConfig.xml

Insert picture description here

1.1 Common configuration analysis

1.1.1 environments label (configuration of database environment, support for multi-environment configuration)

Insert picture description here
Among them:
there are two types of transaction manager (transactionManager):

  • JDBC: This configuration directly uses the commit and rollback settings of JDBC, which relies on the connection obtained from the data source to manage the transaction
    domain.
  • MANAGED: This configuration does almost nothing. It never commits or rolls back a connection, but lets the container manage the entire
    life cycle of the transaction (such as the context of a JEE application server). It will close the connection by default, but some containers do not want this,
    so you need to set the closeConnection property to false to prevent it from closing the default behavior.

There are three types of dataSource:

  • UNPOOLED: The implementation of this data source just opens and closes the connection each time it is requested.
  • POOLED: The realization 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 servers. The container can configure
    the data source centrally or externally , and then place a reference to the JNDI context.

1.1.2 mapper tag (the role is to load the map)

Loading method:

•使用相对于类路径的资源引用,例如:
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
•使用完全限定资源定位符(URL),例如:
<mapper url="file:///var/mappers/AuthorMapper.xml"/>
•使用映射器接口实现类的完全限定类名,例如:
<mapper class="org.mybatis.builder.AuthorMapper"/>
•将包内的映射器接口实现全部注册为映射器,例如:
<package name="org.mybatis.builder"/>

1.1.3 Properties tab

In actual development, it is customary to extract the configuration information of the data source separately into a properties file, this tag can load additional configuration properties file
Insert picture description here

1.1.4 typeAliases tag (type aliases, set a short name for the Java type)

![](https://img-blog.csdnimg.cn/20210112183132344.png
The mybatis framework has already set up some commonly used types of aliases:

Alias Type of mapping
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

2. Mapping configuration file mapper.xml

if judgment

<select id="findByCondition" parameterType="user" resultType="user">
	select * from User
	<where>
		<if test="id!=0">
			and id=#{
    
    id}
		</if>
		<if test="username!=null">
			and username=#{
    
    username}
		</if>
	</where>
</select>

Splicing of loop sql

<select id="findByIds" parameterType="list" resultType="user">
	select * from User
	<where>
		<foreach collection="list" open="id in(" close=")" item="id" separator=",">
			#{
    
    id}
		</foreach>
	</where>
</select>

The foreach tag is used to traverse the collection:

  • collection: Represents the collection elements to be traversed, pay attention not to write #{} when writing
  • open: represents the beginning of the statement
  • close: represents the end part
  • item: represents each element of the traversal collection, the generated variable name
  • sperator: represents the separator

SQL fragment extraction
Sql can extract duplicate sql, use include to quote when using, and finally achieve the purpose of sql reuse.

<!--抽取sql片段简化编写-->
<sql id="selectUser" select * from User</sql>
<select id="findById" parameterType="int" resultType="user">
	<include refid="selectUser"></include> where id=#{
    
    id}
</select>
<select id="findByIds" parameterType="list" resultType="user">
	<include refid="selectUser"></include>
	<where>
		<foreach collection="array" open="id in(" close=")" item="id" separator=",">
			#{
    
    id}
		</foreach>
	</where>
</select>

Guess you like

Origin blog.csdn.net/weixin_39417423/article/details/112541360