springboot mvc web project works fine eventhough resultType in Mapper.xml is different from type in java code

40 Views Asked by At

I'm using springboot and mybatis latest version, JDK17, vscode new to springboot and mybatis.

Every type in java class and interface code is Menu type, and only resultType in Mapper xml is MenuView .

application.yml for springboot


...
mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapper-locations: mappers/*Mapper.xml

...

menuMapper.xml

<mapper namespace="...MenuRepository">

    <select id="findAll" resultType="MenuView"> select * from menu_view </select>
    
</mapper>

menu table don't have likeCount.

menu_view view have likeCount.

MenuView.java

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MenuView {

    private long id;
    private String name;
    private long likeCount;
    
}

Menu.java

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Menu {

    private long id;
    private String name;
    
}

MenuRepository.java

@Mapper
public interface MenuRepository {

    List<Menu> findAll();


}

MenuService.java

public interface MenuService {

    List<Menu> getList();

}

MenuServiceImp.java

@Service
public class MenuServiceImp implements MenuService {

    @Autowired
    private MenuRepository repository;

    @Override
    public List<Menu> getList() {
        List<Menu> list = repository.findAll();

        return list;
    }

}

MenuController.java


@Controller
@RequestMapping("menu")
public class MenuController {

    @Autowired
    private MenuService service;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("list")
    public String list(Model model) {
        List<Menu> list = service.getList();
        model.addAttribute("list", list);
  
        // System.out.println(list); print "MenuView[id=, name=, likeCount=]"
       
        // System.out.println(list.get(0) instanceof MenuView);
        //java.lang.Error: Unresolved compilation problem:
        //      Incompatible conditional operand types Menu and MenuView
      
        // System.out.println(list.get(0) instanceof Menu); false
      
        return "menu/list";
    }

}

In list.html the data is properly printed. There is no way to get likeCount from Menu but it prints likeCount properly.

It seems mybatis or spring is implicitly converting the return type from Menu to MenuView.

How does it work?

To get likeCount with menu table which has no likeCount but has foreign key for it I made menu_view view in database. and I was supposed to change all Menu type in the java code but didn't changed by mistake. it's not suppossed to work because type is different. But it works. why?

0

There are 0 best solutions below