按照嵌套查询方式进行一对多查询
我的方法:在配置文件中写出一对多查询的sql语句
先看看数据表结构,假设在一个论坛问答网站有两个表,一个是用户表,一个是问题表,现在需要查询出id为1的用户写了哪些问题
问题表:

用户表:

SQL语句:SELECT*from questions where questions.user_id=1
查询结果:

先创建POJO类
对照数据表,创建Question类

对照数据表,创建User类

(Getter和Setter方法自己写)
写出配置文件,将SQL语句卸载配置文件中,这里的输入参数我用的是int,返回类型是Question
QuestionMapper.xml


在总的配置文件中注册刚才的Mapper
写出测试方法

运行结果:

小结:
一对多、多对多应该有更mybatis的方法,不过现在还没学到。还有QuestionMapper文件中的ResultType都写成类的名字而不需要因为查询多个对象去写成list之类的东西。
网友评论