Mybatis 入门之resultMap与resultType讲解实例

resultMap:适合使用返回值是自定义实体类的情况

resultType:适合使用返回值得数据类型是非自定义的,即jdk的提供的类型

resultMap : 

type:映射实体类的数据类型

id:resultMap的唯一标识

column:库表的字段名

property:实体类里的属性名


配置映射文件:





	
	
		
		
		
		
		
		
	
	

	
	
	
	

	





实体类Person.java

package com.hao947.model;
import java.util.Date;
public class Person {
	private Integer personId;
	private String name;
	private Integer gender;
	private String personAddr;
	private Date birthday;
	@Override
	public String toString() {
		return "Person [personId=" + personId + ", name=" + name + ", gender="
				+ gender + ", personAddr=" + personAddr + ", birthday="
				+ birthday + "]";
	}
}

 测试类 
  

public class PersonTest {
	SqlSessionFactory sqlSessionFactory;
	@Before
	public void setUp() throws Exception {
		// 读取资源流
		InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
		// 初始化session工厂
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
	}

	

	@Test
	public void selectPersonById() {
		// 创建一个sqlsession
		SqlSession session = sqlSessionFactory.openSession();
		try {
			Person p = session.selectOne(
					"com.hao947.sql.mapper.PersonMapper.selectPersonById", 1);
			System.out.println(p);
		} finally {
			session.close();
		}
	}
	@Test
	public void selectPersonCount() {
		// 创建一个sqlsession
		SqlSession session = sqlSessionFactory.openSession();
		try {
			Integer p = session.selectOne(
					"com.hao947.sql.mapper.PersonMapper.selectPersonCount");
			System.out.println(p);
		} finally {
			session.close();
		}
	}
	@Test
	public void selectPersonByIdWithMap() {
		// 创建一个sqlsession
		SqlSession session = sqlSessionFactory.openSession();
		try {
			Map map = session.selectOne(
					"com.hao947.sql.mapper.PersonMapper.selectPersonByIdWithMap",1);
			System.out.println(map);
		} finally {
			session.close();
		}
	}
}


你可能感兴趣的:(Mybatis)