MyBatis: mapper.xml mapping file

The mapper.xml mapping file defines the sql that operates the database. Each sql is a statement. The mapping file is the core of mybatis.

The following test methods need to be run within the test class

public class UserMapperTest extends TestCase {

	private SqlSessionFactory sqlSessionFactory;

	@Override
	protected void setUp() throws Exception {
		// mybatis配置文件
		String resource = "mybatisConfig.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		// 使用SqlSessionFactoryBuilder创建sessionFactory
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
 
  //测试方法 

parameterType (input type)

1. Pass simple types

# {} 与 $ {}

# {} Is to set the parameter value to the prepared statement in prepareStatement, # {} in the sql statement represents a placeholder, namely "?".

 <!-- 根据id查询用户信息 -->
<select id="findUserById" parameterType="int" resultType="user">
    select * from user where id = #{id}
</select>

Using placeholder # {} can effectively prevent SQL injection. When you use it, you do n’t need to care about the type of the parameter value. Mybatis will automatically convert the java type and jdbc type. # {} Can receive simple type values ​​or pojo attribute values. If parameterType transmits a single simple type value, # {} can be value or other name in parentheses.

$ {} And # {} are different, through $ {} you can splice the content passed in parameterType in sql without jdbc type conversion, $ {} can receive simple type value or pojo attribute value, if parameterType transmits a single simple type Value, $ {} can only be value in parentheses. Using $ {} can not prevent SQL injection, but sometimes it is very convenient to use $ {}, the following example:

 <!-- 根据名称模糊查询用户信息 -->
<select id="selectUserByName" parameterType="string" resultType="user">
    select * from user where username like '%${value}%'
</select>

If this example uses # {}, the incoming string must have a% sign, and% is artificially spliced ​​in the parameter, which is obviously a bit troublesome. If the $ {} is spliced ​​into% in SQL, the mapper interface is called Passing parameters is much more convenient.

 //如果使用占位符号则必须人为在传参数中加%
List<User> list = userMapper.selectUserByName("%管理员%");

 //如果使用${}原始符号则不用人为在参数中加%
List<User>list = userMapper.selectUserByName("管理员");

Another example is order by sorting. If the column name is passed to SQL through parameters and sorted according to the passed column name, it should be written as: ORDER BY $ {columnName}. If you use # {}, this function cannot be achieved.

2. Pass the pojo packaging object

In the development, the query conditions are passed through pojo. The query conditions are comprehensive query conditions, including not only user query conditions but also other query conditions (such as the user purchased product information is also used as a query condition), then you can use the packaging object to pass input parameters.

Define the packaging object and wrap the query conditions in a class combination.

public class QueryUserVo {

	// 自定义用户扩展类
	private UserCustom userCustom;

	public UserCustom getUserCustom() {
		return userCustom;
	}

	public void setUserCustom(UserCustom userCustom) {
		this.userCustom = userCustom;
	}
}
public class UserCustom extends User {

}

mapper.xml mapping file

<select id="findUserList" parameterType="org.haiwen.pojo.QueryUserVo" resultType="user">
	select * from user where id = #{userCustom.id} and username like '%${userCustom.username}%'
</select>
public List<User> findUserList(QueryUserVo queryUserVo) throws Exception;

test

@Test
public void testFindUserList() throws Exception {
	SqlSession sqlSession = sqlSessionFactory.openSession();
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	UserCustom userCustom = new UserCustom();
	userCustom.setId(1);
	userCustom.setUsername("马");
	QueryUserVo queryUserVo = new QueryUserVo();
	queryUserVo.setUserCustom(userCustom);
	List<User> list = userMapper.findUserList(queryUserVo);
	for (User user : list) {
		System.out.println(user);
	}
}

Description: The bottom of mybatis obtains the attribute value from pojo through ognl: # {userCustom.id}, userCustom is the attribute of the incoming packaging object. The attribute value needs to be obtained by the method of "wrapping class attribute. Attribute".

3. Pass HashMap

mapper.xml mapping file

<select id="findUserByHashmap" parameterType="hashmap" resultType="user">
	select * from user where id = #{id} and username like '%${username}%'
</select>
public List<User> findUserByHashmap(Map<String, Object> map) throws Exception;

test

@Test
public void testFindUserByHashmap() throws Exception {
	SqlSession sqlSession = sqlSessionFactory.openSession();
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	Map<String, Object> map = new HashMap();
	map.put("id", 1);
	map.put("username", "马");
	List<User> list = userMapper.findUserByHashmap(map);
	for (User user : list) {
		System.out.println(user);
	}
}

resultType (output type)

1. Simple output type

mapper.xml mapping file

<select id="findUserCount" resultType="int">
   select count(1) from user
</select>
public int findUserCount() throws Exception;

test

@Test
public void testFindUserCount() throws Exception {
	SqlSession session = sqlSessionFactory.openSession();
	UserMapper userMapper = session.getMapper(UserMapper.class);
	int count = userMapper.findUserCount();
	System.out.println(count);
	session.close();
}

to sum up

The result set that must be queried for the output simple type has a record, and finally converts the value of the first field to the output type.

Use session's selectOne to query a single record.

2. Output pojo objects

mapper.xml mapping file

<select id="findUserById" parameterType="int" resultType="org.haiwen.entity.User">
	select * from user where id = #{id}
</select>
public User findUserById(int id) throws Exception;

test

@Test
public void testFindUserById() throws Exception {
	SqlSession session = sqlSessionFactory.openSession();
	UserMapper userMapper = session.getMapper(UserMapper.class);
	User user = userMapper.findUserById(1);
	System.out.println(user);
	session.close();
}

3. Output pojo list

mapper.xml mapping file

<select id="findUserByUsername" parameterType="java.lang.String" resultType="org.haiwen.entity.User">
	select * from user where username like '%${value}%'
</select>
public List<User> findUserByUsername(String username) throws Exception;

test

@Test
public void testFindUserByUsername() throws Exception {
	SqlSession sqlSession = sqlSessionFactory.openSession();
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	List<User> list = userMapper.findUserByUsername("马");
	for (User user : list) {
		System.out.println(user);
	}
}

to sum up

The output pojo object and output pojo list are the same as the resultType defined in sql.

To return a single pojo object, ensure that the result set from the sql query is a single item, internally use the session.selectOne method call, and the mapper interface uses the pojo object as the method return value.

Returning to the pojo list indicates that there may be multiple result sets from the query. The session.selectList method is used internally, and the Mapper interface uses a List <pojo> object as the method return value.

4. Output resultMap

The resultType maps the query result to pojo. The attribute name of the pojo and the column name of the sql query must be the same to be successfully mapped.

resultMap can also map the query results to pojo. It is not necessary for the attribute names of the pojo to be the same as the column names of the sql query, but you need to make a correspondence between the field names and the attribute names through resultMap.

mapper.xml mapping file

<!--定义resultMap
	将select id user_id,username user_username from user 和User类中的属性作一个映射关系
	
	type:resultMap最终映射的java对象类型,可以使用别名
	id:对resultMap的唯一标识-->
<resultMap type="org.haiwen.entity.User" id="userResultMap">
	<!--id表示查询结果集中唯一标识
		column:查询出来的列名
		property:type指定的pojo类型中的属性名
		最终resultMap对column和property作一个映射关系(对应关系)-->
	<id column="user_id" property="id" />
	<!--result:对普通名映射定义
		column:查询出来的列名
		property:type指定的pojo类型中的属性名
		最终resultMapx对column和property作一个映射关系(对应关系)-->
	<result column="user_password" property="password" />
</resultMap>

<select id="findUserListResultMap" resultMap="userResultMap">
	select id user_id,password user_password from user
</select>
public List<User> findUserListResultMap() throws Exception;

test

@Test
public void testFindUserListResultMap() throws Exception {
	SqlSession sqlSession = sqlSessionFactory.openSession();
	UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
	List<User> list = userMapper.findUserListResultMap();
	for (User user : list) {
		System.out.println(user);
	}
}
Published 202 original articles · praised 37 · 30,000+ views

Guess you like

Origin blog.csdn.net/lovecuidong/article/details/101270319