首页 > 网站 > WEB开发 > 正文

Mybatis(五) resultType 多表查询 (包装类)

2024-04-27 15:18:52
字体:
来源:转载
供稿:网友

查看这张时必须有上一张的基础

这里使用了包装类,将多个表查询数来的复杂结果存储在包装类中返回回来

CREATE DATABASE my_db;CREATE TABLE user( id INT(11) PRIMARY KEY AUTO_INCREMENT, parentId INT(11), sonId INT(11), name VARCHAR(255), birthday DATE )DEFAULT CHARSET=utf8;CREATE TABLE `orders` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `userId` INTEGER NOT NULL, `create` DATETIME DEFAULT NULL, `detailId` INTEGER DEFAULT NULL, PRIMARY KEY (`id`) )DEFAULT CHARSET=utf8;

目录结构。 这里写图片描述

这里我新创建了:

Orders.java : Orders对象。OrdersCustem.java: Order包装对象。 (重点)OrderDao.java : 数据接口 OrderDao.xml: mapper映射文件。(重点)

OrdersCustem对象和OrderDao 必须一一对应。

代码如下: OrdersCustem.java:

package com.zll.mybatis.bean;import java.util.Date;public class OrderCustem extends Orders{ private String username; private Date userBirthday; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } @Override public String toString() { return "OrderCustem [username=" + username + ", userBirthday=" + userBirthday + ", getId()=" + getId() + ", getDetailId()=" + getDetailId() + ", getCreate()=" + getCreate() + ", getUserId()=" + getUserId() + "]"; }}

OrderDao.java :

package com.zll.mybatis.dao;import com.zll.mybatis.bean.OrderCustem;public interface OrderDao { public List<OrderCustem> findOrderById() throws Exception;}

OrderDao.xml(重点)

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.zll.mybatis.dao.OrderDao"> <!-- 模糊查询 ${}符号表示sql使用拼接方式,这样会参数sql注入露点,所以大家要注意 --> <select id="findOrderById" resultType="com.zll.mybatis.bean.OrderCustem"> select orders.*,user.name username,user.birthday userBirthday from orders,user where orders.userId = user.id; </select></mapper>

测试代码:

/** * Unit test for simple App. */public class TestResultTypeMap extends TestCase { SqlsessionFactory sqlSessionFactory; @Override protected void setUp() throws Exception { super.setUp(); String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } public void findOrderById() throws Exception { SqlSession openSession = sqlSessionFactory.openSession(); OrderDao mapper = openSession.getMapper(OrderDao.class); List<OrderCustem> findOrderById = mapper.findOrderById(); for(int i=0; i<findOrderById.size(); i++){ System.out.println(findOrderById.get(i)); } openSession.close(); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表