Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

When we use Mybatis, we will set a resultType, which is usually specified as java.util.Map, so that we can use List, Map to receive the returned results.

The desired effect is to receive the same SQL parameter in two different types of operations at the Service layer.

As in the following code.


List<ADemo> list1 = demoDao.findDemo();

Long total = demoDao.findDemo();

Copy the code

Let’s take a look at the implementation.

knowledge

The first solution you want is generics, and only generics can specify conversions between different types.

Here we will talk about how to add generics to methods to accommodate different return value types.

Method plus generic, naturally used to

modifier, as shown in the following code.

<T> T findDemo();
Copy the code

The above code can then use any return type to receive.

It is important to note, however, that an error will be reported when writing a resultType= java.util.map.

So we rewrote it in a different way.

<T> List<T> findDemo();
Copy the code

So, we changed the way, as shown in the code above, and sure enough, it worked perfectly, with different injection methods for generics as follows:


List<ADemo> list1 = demoDao.findDemo();

List<Map<String,Long>> list2 = demoDao.findDemo();

Copy the code

List2.get (0).get(‘total’); list2.get(0).

In this way, although the desired effect is not fully realized, the problem is solved within the permissible scope.