Section II: mybatis summary of the return value

    mybatis framework allows us to only need to write an interface programming, then write mapper mapping file, without writing a class that implements the interface. In fact, this is a dynamic mybatis by proxy, the contents mapper mapping file into real operative. Therefore, we in programming, special attention needs to write interfaces and mapping files. This section explains the interface type of the return value in write mode mapper file.

Our thinking, return type is generally divided into

  • Numeric types, such as records of the number of queries
  • Single object
  • A plurality of objects, use the package List
  • Single object, using the map package
  • A plurality of objects, use the map package

  Since the establishment of each project is more complex, you can refer to Section I: mybatis entry to build a simple project, and then to test this section.

  Note This section concerns mapper interface is written in resultType type and mapper file the return value.

1, return type number type


1, mapper interface, we simply query all the records, type of return value Long.

public  interface Person Mapper 
{ 
    Long getTotalNumberOfPerson (); 
}

2, mapper mapping file

<select id="getTotalNumberOfPerson" resultType="long">
    select count(*) from person
</select>

Note mapper file, you only need to type long resultType can.

3, the test

public class Main
{
    public static void main(String[] args)
        throws IOException
    {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        Long totalNumberOfPerson= mapper.getTotalNumberOfPerson();
        System.out.println(totalNumberOfPerson); //10
        sqlSession.close();
    }
}

2, single object query


This query returns directly to the corresponding database tables and related entities, and only one record, are generally in accordance id to query, that is, Section I: Getting Started mybatis demonstrated in the sample, we again explained next.

1, mapper interfaces

public interface PersonMapper
{
    Person getPerson(Integer id);
}

2, mapper mapping file

<select id="getPerson" resultType="com.yefengyu.mybatis.entity.Person">
     select id, first_name firstName, last_name lastName, age, email, address  from person where id = #{id}
</select>

3, the test

public class Main
{
    public static void main(String[] args)
        throws IOException
    {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        Person person = mapper.getPerson(1);
        System.out.println(person);
        sqlSession.close();
    }
}

Summary: In a single query object is returned when an entity type, simply resultType set to full class name.

3, a plurality of query objects, use the list encapsulation


Such a query is typically based on certain conditions, a lot of query results, then use the List encapsulated.

1, mapper interfaces, according to the address query multiple Person objects

public interface PersonMapper
{
    List<Person> getPersons(String address);
}

2, mapper mapping file, note mapper interface types can return List for the type, the resultType mapper mapping file only needs to set the object included in the List.

<select id="getPersons" resultType="com.yefengyu.mybatis.entity.Person">
    select id, first_name firstName, last_name lastName, age, email, address from person where address = #{address}
</select>

3, the test

public class Main
{
    public static void main(String[] args)
        throws IOException
    {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        List<Person> persons = mapper.getPersons("beijing");
        for (int i = 0; i < persons.size(); i++)
        {
            System.out.println(persons.get(i));
        }
        sqlSession.close();
    }
}

4 results:

Person{id=1, firstName='Schmitt', lastName='Carine', age=25, email='null', address='beijing'}
Person{id=2, firstName='King', lastName='Jean', age=36, email='[email protected]', address='beijing'}
Person{id=8, firstName='Gao', lastName='Diego', age=45, email='[email protected]', address='beijing'}
Person{id=9, firstName='Piestrzeniewicz', lastName='Schmitt', age=36, email='[email protected]', address='beijing'}
Person{id=10, firstName='Frdrique', lastName='Juri', age=25, email='[email protected]', address='beijing'}

4, a single query object using the map package


This case, similar to the second section, is a single object, but we need to return a map, to encapsulate into a single object map, the name of the attribute name of the database corresponding to the column as a key, as a result of the return value.

1, mapper interfaces

public interface PersonMapper
{
    Map<String, Object> getPersonMap(Integer id);
}

2, mapper mapping file, then the need to resultType to map

<select id="getPersonMap" resultType="map">
    select id, first_name firstName, last_name lastName, age, email, address from person where id = #{id}
</select>

3, the test

public class Main
{
    public static void main(String[] args)
        throws IOException
    {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        Map<String, Object> personMap = mapper.getPersonMap(1);
        System.out.println(personMap);
        sqlSession.close();
    }
}

4、结果如下,注意在使用map接收返回值的时候,如果某个字段为null,那么就不会封装到map中,比如下面的结果中就没有Email字段的结果。

{firstName=Schmitt, lastName=Carine, address=beijing, id=1, age=25}

5、查询多个对象,使用map封装


这个情况,一般是查询多条记录,使用主键作为key,使用对象作为value,见下面mapper接口。

1、mapper接口

public interface PersonMapper
{
    @MapKey("id")
    Map<Integer, Person> getPersonsMap(String address);
}

2、mapper映射文件

<select id="getPersonsMap" resultType="map">
    select id, first_name firstName, last_name lastName, age, email, address from person where address = #{address}
</select>

3、测试

public class Main
{
    public static void main(String[] args)
        throws IOException
    {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
        Map<Integer, Person> personMap = mapper.getPersonsMap("beijing");
        for (Map.Entry<Integer, Person> personEntry : personMap.entrySet())
        {
            System.out.println(personEntry.getKey() + " : " + personEntry.getValue());
        }
        sqlSession.close();
    }
}

4、结果

1 : {firstName=Schmitt, lastName=Carine, address=beijing, id=1, age=25}
2 : {firstName=King, lastName=Jean, address=beijing, id=2, age=36, email=Jean@163.com}
8 : {firstName=Gao, lastName=Diego, address=beijing, id=8, age=45, email=66666@qq.com}
9 : {firstName=Piestrzeniewicz, lastName=Schmitt, address=beijing, id=9, age=36, email=44444@qq.com}
10 : {firstName=Frdrique, lastName=Juri, address=beijing, id=10, age=25, [email protected]}

注意:mapper接口需要使用MapKey注解指定将某个属性的值作为map的key。本例中使用person表的主键id对应的实体的属性id作为key。除此之外,mapper映射文件中resultType设置为map。此外如果某个字段为null,那么就不插入到map中。

6、总结


  • 数字类型,比如查询记录的个数resultType为 int 或者 long等。
  • 单个对象。resultType为对象全类名
  • 多个对象,使用List封装。resultType为对象全类名。
  • 单个对象,使用map封装。resultType为map。
  • 多个对象,使用map封装。resultType为map。注意mapper接口的方法需要使用MapKey注解指定key为哪个属性。

Guess you like

Origin www.cnblogs.com/ye-feng-yu/p/10987587.html