问题:两个对象User和Score,它们之间的关系为一对多。

底层数据库为postgresql,ORM框架为mybatis。

关键代码如下:

mybatis配置文件如下:

mybatis.xml文件内容为:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <setting name="cacheEnabled" value="true" />
  8. <setting name="lazyLoadingEnabled" value="true" />
  9. <setting name="multipleResultSetsEnabled" value="true" />
  10. <setting name="useColumnLabel" value="true" />
  11. <setting name="useGeneratedKeys" value="true" />
  12. <setting name="defaultExecutorType" value="SIMPLE" />
  13. <setting name="defaultStatementTimeout" value="25000" />
  14. </settings>
  15. <typeAliases>
  16. <typeAlias type="com.mybatis.domain.User" alias="User" />
  17. <typeAlias type="com.mybatis.domain.Score" alias="Score" />
  18. </typeAliases>
  19. <environments default="development">
  20. <environment id="development">
  21. <transactionManager type="JDBC" />
  22. <dataSource type="POOLED">
  23. <property name="driver" value="org.postgresql.Driver" />
  24. <property name="url" value="jdbc:postgresql://localhost:5432/mybatis" />
  25. <property name="username" value="postgres" />
  26. <property name="password" value="admin" />
  27. </dataSource>
  28. </environment>
  29. </environments>
  30. <mappers>
  31. <mapper resource="com/mybatis/domain/User.xml" />
  32. <mapper resource="com/mybatis/domain/Score.xml" />
  33. </mappers>
  34. </configuration>

User.java代码为:

  1. package com.mybatis.domain;
  2. public class User {
  3. private Integer id;//用户id
  4. private String username;//用户名
  5. private String password;//密码
  6. private String address;//地址
  7. public User(){
  8. }
  9. public User(String username,String password,String address){
  10. this.username = username;
  11. this.password = password;
  12. this.address =address;
  13. }
  14. public User(Integer id,String username,String password,String address){
  15. this.id = id;
  16. this.username = username;
  17. this.password = password;
  18. this.address =address;
  19. }
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(Integer id) {
  24. this.id = id;
  25. }
  26. public String getUsername() {
  27. return username;
  28. }
  29. public void setUsername(String username) {
  30. this.username = username;
  31. }
  32. public String getPassword() {
  33. return password;
  34. }
  35. public void setPassword(String password) {
  36. this.password = password;
  37. }
  38. public String getAddress() {
  39. return address;
  40. }
  41. public void setAddress(String address) {
  42. this.address = address;
  43. }
  44. public String toString(){
  45. return "当前用户为:id = "+id+",username = "+username+",password = "+password+",address = "+address;
  46. }
  47. }

Score.java代码如下:

  1. package com.mybatis.domain;
  2. public class Score {
  3. private Integer id ;//主键id
  4. private User user;//所属用户
  5. private int math ;//数学成绩
  6. private int chinese ;//语文成绩
  7. private int english ;//英语成绩
  8. private int computer ;//计算机成绩
  9. public Score(){
  10. }
  11. public Score(User user, int math,int chinese,int english,int computer){
  12. this.user = user;
  13. this.math = math;
  14. this.chinese = chinese;
  15. this.english = english;
  16. this.computer = computer;
  17. }
  18. public Integer getId() {
  19. return id;
  20. }
  21. public void setId(Integer id) {
  22. this.id = id;
  23. }
  24. public User getUser() {
  25. return user;
  26. }
  27. public void setUser(User user) {
  28. this.user = user;
  29. }
  30. public int getMath() {
  31. return math;
  32. }
  33. public void setMath(int math) {
  34. this.math = math;
  35. }
  36. public int getChinese() {
  37. return chinese;
  38. }
  39. public void setChinese(int chinese) {
  40. this.chinese = chinese;
  41. }
  42. public int getEnglish() {
  43. return english;
  44. }
  45. public void setEnglish(int english) {
  46. this.english = english;
  47. }
  48. public int getComputer() {
  49. return computer;
  50. }
  51. public void setComputer(int computer) {
  52. this.computer = computer;
  53. }
  54. public String toString(){
  55. return "id = "+ this.id+",math = "+this.math+",chinese = "+this.chinese+",english = "+this.english+",computer = "+this.computer+
  56. ", userid = "+this.user.getId()+",username = "+this.user.getUsername()+",password = "+this.user.getPassword()+
  57. ",address = "+this.user.getAddress();
  58. }
  59. }

user.xml中的关键代码为:

  1. <resultMap type="User" id="userResult">
  2. <id property="id" column="userid"/>
  3. <result property="username" column="username"/>
  4. <result property="password" column="password"/>
  5. <result property="address" column="address"/>
  6. </resultMap>

这里的对象的属性id对应的数据库表列名为userid,这是user对象为pg_score表中

的标示。

score.xml代码如下:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="ScoreDaoMapping">
  5. <resultMap type="Score" id="score">
  6. <constructor>
  7. <idArg column="id" javaType="int" />
  8. <arg column="userid" javaType="int" />
  9. <arg column="math" javaType="int" />
  10. <arg column="chinese" javaType="int" />
  11. <arg column="english" javaType="int" />
  12. <arg column="computer" javaType="int" />
  13. </constructor>
  14. </resultMap>
  15. <resultMap id="joinSelectScore" type="Score" >
  16. <id property="id" column="id"/>
  17. <result property="math" column="math"/>
  18. <result property="chinese" column="chinese"/>
  19. <result property="english" column="english"/>
  20. <result property="computer" column="computer"/>
  21. <association property="user" column="userid" javaType="User" resultMap="UserDaoMapping.userResult"/>
  22. </resultMap>
  23. <insert id="insertScore" parameterType="Score">
  24. insert into pg_score(math,chinese,english,computer,userid) values(#{math},#{chinese},#{english},#{computer},#{user.id})
  25. </insert>
  26. <select id="findScoreByUser" resultMap="joinSelectScore" resultType="list" parameterType="map">
  27. select
  28. s.id as id,
  29. s.math as math,
  30. s.chinese as chinese,
  31. s.english as english,
  32. s.computer as computer,
  33. u.id as userid,
  34. u.username as username,
  35. u.password as password,
  36. u.address as address
  37. from pg_score s left outer join pg_userinfo u on s.userid = u.id where u.id=#{userid}
  38. </select>
  39. </mapper>

ScoreDao.java中的关键代码为:

  1. private  String resource = "com/mybatis/configuration/mybatis.xml";
  2. public List<Score> selectScoreByUser(User user) throws IOException{
  3. Reader reader = Resources.getResourceAsReader(resource);
  4. SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
  5. SqlSession session = ssf.openSession();
  6. reader.close();
  7. Map<String,Integer> params = new HashMap<String,Integer>();
  8. params.put("userid", user.getId());
  9. List<Score> scoreList = session.selectList("ScoreDaoMapping.findScoreByUser", params);
  10. session.commit();
  11. session.close();
  12. return scoreList;
  13. }

ScoreService.java代码如下:

  1. package com.mybatis.service;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import com.mybatis.dao.ScoreDao;
  5. import com.mybatis.domain.Score;
  6. import com.mybatis.domain.User;
  7. public class ScoreService {
  8. private ScoreDao scoreDao = new ScoreDao();
  9. public ScoreDao getScoreDao() {
  10. return scoreDao;
  11. }
  12. public void setScoreDao(ScoreDao scoreDao) {
  13. this.scoreDao = scoreDao;
  14. }
  15. public List<Score> getScoreByUser(User user) throws IOException{
  16. return scoreDao.selectScoreByUser(user);
  17. }
  18. public void insertScore(Score score) throws IOException{
  19. scoreDao.insert(score);
  20. }
  21. }

Test.java代码如下:

  1. package com.mybatis.test;
  2. import java.util.List;
  3. import com.mybatis.domain.Score;
  4. import com.mybatis.domain.User;
  5. import com.mybatis.service.ScoreService;
  6. import com.mybatis.service.UserService;
  7. public class Test {
  8. private UserService userService = new UserService();
  9. private ScoreService scoreSerice = new ScoreService();
  10. public static void main(String[] args) throws Exception{
  11. Test test = new Test();
  12. //test.insertScore();
  13. List<Score> scoreList = test.getScore();
  14. Score score = null;
  15. for(int i=0;i<scoreList.size();i++){
  16. System.out.println("第"+(i+1)+"个score对象为:");
  17. score = scoreList.get(i);
  18. System.out.println(score);
  19. }
  20. }
  21. public void insertScore() throws Exception{
  22. List<User> userList = userService.getPageUsers(10, 0);
  23. User user = userList.get(2);
  24. Score score = new Score();
  25. score.setUser(user);
  26. score.setChinese(80);
  27. score.setComputer(90);
  28. score.setEnglish(91);
  29. score.setMath(98);
  30. scoreSerice.insertScore(score);
  31. }
  32. public List<Score> getScore() throws Exception{
  33. List<User> userList = userService.getPageUsers(10, 0);
  34. User user = userList.get(0);
  35. List<Score> scoreList = scoreSerice.getScoreByUser(user);
  36. return scoreList;
  37. }
  38. /*  public User getUserById(int id) throws Exception{
  39. return userService.getUserById(id);
  40. }*/
  41. }

mybatis实现一对多连接查询的更多相关文章

  1. mybatis 13: 一对多关联查询

    业务背景 根据客户id查询客户基本信息,以及客户存在的订单信息 两张数据表 客户表 订单表 实体类 客户实体类:Customer private Integer id; private String ...

  2. MyBatis:一对多关联查询

    MyBatis从入门到放弃四:一对多关联查询 前言 上篇学习了一对一关联查询,这篇我们学习一对多关联查询.一对多关联查询关键点则依然是配置resultMap,在resultMap中配置collecti ...

  3. mybatis collection 一对多关联查询,单边分页的问题总结!

    若想直接通过sql实现多级关联查询表结构得有2 个必不可少的字段:id ,parentId,levelId id:主键id, parentId:父id levelId:表示第几级(表本身关联查询的时候 ...

  4. 使用mybatis进行一对多嵌套查询时出错:输出结果:Country{id=2, name='美国', minister=[null]}

    即Minister类作为Country类的关联属性. 查询的输出结果是:Country{id=2, name='美国', minister=[null]} <!--mapper.xml内容--& ...

  5. mybatis处理一对多的查询

    //查询出某个班级对应的所有老师和学生 1.使用嵌套结果 <select id="findClasses3" parameterType="int" re ...

  6. Mybatis中的多表查询 多对一,一对多

    示例:用户和账户 一个用户可以有多个账户 一个账户只能属于一个用户(多个账户也可以属于同一个用户) 步骤: 1.建立两张表:用户表,账户表 让用户表和账户表之间具备一对多的关系:需要使用外键在账户表中 ...

  7. MyBatis数据持久化(七)多表连接查询

    本节继续以多表连接查询的案例介绍使用resultMap的好处,对于两张以上的表进行关联查询,当我们有选择的从不同表查询所需字段时,使用resultMap是相当方便的.例如我们有两张表,分别为用户表Us ...

  8. 7.mybatis一对多关联查询

    和第5节一对一查询类似,但是不同的是,一对一使用的是association,而一对多使用collection. 实例: 1个班级Class,对应1个老师Teacher,对应多个学生Student 1. ...

  9. MyBatis从入门到放弃四:一对多关联查询

    前言 上篇学习了一对一关联查询,这篇我们学习一对多关联查询.一对多关联查询关键点则依然是配置resultMap,在resultMap中配置collection属性,别忽略了ofType属性. 搭建开发 ...

随机推荐

  1. 第9章 应用层(4)_超文本传输协议HTTP

    5. 超文本传输协议HTTP 5.1 统一资源定位符URL (1)URL的一般形式:<协议>://<主机>:<端口>/<路径> ①协议后面必须写上“:/ ...

  2. Delphi获取本机的MAC地址

    Delphi获取本机的MAC地址: uses   NB30; function GetAdaPterInfo(lana: Char): string; var   Adapter: TAdapterS ...

  3. three.js学习:纹理Texture之平面纹理

    index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...

  4. es6基础(6)--数组扩展

    //数组扩展 { let arr=Array.of(3,4,6,7,9,11);//可以是空 console.log('arr=',arr);//[3,4,6,7,9,11] } { //Array. ...

  5. javascript(面向对象,作用域,闭包,设计模式等)

    javascript(面向对象,作用域,闭包,设计模式等) 1. 常用js类定义的方法有哪些? 参考答案:主要有构造函数原型和对象创建两种方法.原型法是通用老方法,对象创建是ES5推荐使用的方法.目前 ...

  6. properties文件读取

    package properties; import java.io.FileInputStream; import java.io.FileNotFoundException; import jav ...

  7. c# 后台AJAX

    public class BackA { #region 后台 AJAX public static string GetPage(string posturl) { Stream outstream ...

  8. StanFord ML 笔记 第十部分

    第十部分: 1.PCA降维 2.LDA 注释:一直看理论感觉坚持不了,现在进行<机器学习实战>的边写代码边看理论

  9. MySQL C API(23)

    C API 提供了对 MySQL c/s 模型的底层访问.C API 代码在 mysqlclient 库中实现.可以从该库中引用到的变量及含义: 环境变量 含义 MYSQL_UNIX_PORT 本地连 ...

  10. [Lua]table(二):删除与排序

    function PrintTable(tb) for k,v in pairs(tb) do print(v) end print("-------------------") ...