问题:两个对象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. MySQL5.7修改默认密码、随机密码

    mysql5.7以后默认生成随机密码,修改root用户密码 1.修改配置参数Linux: /etc/my.cnf Windows:  C:\ProgramData\MySQL\MySQL Server ...

  2. C#列的一些操作

    //变更列名 DataTableA.Columns["原来的列名"].ColumnName="新的列名";

  3. 轻型DNS服务器dnsmasq

    源码安装 源码下载地址 apt 安装 apt install dnsmasq 编辑配置 vim /etc/dnsmasq.conf resolv-file=/etc/resolv.dnsmasq.co ...

  4. Elasticsearch的JavaAPI

    获取客户端对象 public class App { private TransportClient client; //获取客户端对象 @Before public void getClinet() ...

  5. 图像_pytesseract

    所需模块 ①安装PIL:pip install Pillow(之前的博客中有写过) ②安装pytesser3:pip install pytesser3 ③安装pytesseract:pip inst ...

  6. es6(14)--iterator for ...of循环

    //iterator for ...of循环 { let arr=['hello','world']; let map=arr[Symbol.iterator](); console.log(map. ...

  7. linux下mysql-5.6忘记root密码,重置root密码详细过程

      在linux平台下使用mysql过程中忘记了root密码,对于运维和DBA来讲都是一件头疼的事情,下面来讲解下怎么进行重置mysql数据库root 密码: 1.首先停止mysql服务进程: 1 s ...

  8. Java并发编程:Java Thread 的 run() 与 start() 的区别

    1. sleep 和 wait 方法解释 sleep()方法是Thread类里面的,主要的意义就是让当前线程停止执行,让出cpu给其他的线程,但是不会释放对象锁资源以及监控的状态,当指定的时间到了之后 ...

  9. nginx, supervisor, celery

      资料: supervisor和nginx使用 1 .supervisor 管理进程工具 2 .nginx 反向代理, 负载均衡 安装nginx $ sudo apt-get update $ su ...

  10. 【转】netstat 的10个基本用法

    5. 获取进程名.进程号以及用户 ID 查看端口和连接的信息时,能查看到它们对应的进程名和进程号对系统管理员来说是非常有帮助的.举个栗子,Apache 的 httpd 服务开启80端口,如果你要查看 ...