Mybatis映射文件学习(一) 一对一映射 resultType

1,声明

本博客所有内容来源于网络、书籍、和各类手册。
内容均为非盈利,旨为学习记录,方便查询、总结备份、开源分享。
部分转载内容均有注明出处,如有侵权请告知,马上删除

参考链接
[Mybatis(三) 映射文件详解(https://www.cnblogs.com/whgk/p/6718979.html)

2, 工具

Idea 2019.2
maven 3.61
mysql 8.017
mybatis

3,依赖jar包 Dependencies

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <!-- spring版本号 -->
    <spring.version>5.1.9.RELEASE</spring.version>
    <!-- Mybatis版本号 -->
    <mybatis.version>3.4.6</mybatis.version>
    <!-- log4j 版本号 -->
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>

    <!-- 导入Mysql数据库链接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.16</version>
    </dependency>

    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

4,代码结构

在这里插入图片描述

5, Mybatis Generator 配置文件

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!-- 取别名,或者别的其他全局配置信息,就在这里编写 -->
    <typeAliases>
        <!-- 别名为类名首字母大小写都可以 -->
        <package name="com.hardes.pojos"/>
    </typeAliases>
    <!-- 原先这里还有连接数据库的一些配置,与spring整合后,都交由spring来管理 -->

    <!-- 加载mapper映射文件,使用通用的配置 -->
    <mappers>
        <package name="com.hardes.mappers"/>

    </mappers>
</configuration>

6, Spring 配置文件

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd ">
    <!-- 引用java配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
        <property name="maxActive" value="10"/>
        <property name="maxIdle" value="5"/>
    </bean>

    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis的全局配置文件的路径 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 批量配置,这里是批量配置mapper代理,那么下面就不用配置id了。
       我们想要获取哪个mapper代理用这个格式:类名首字母小写
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hardes.mappers"></property>
        <!-- 默认不需要配置,但是如果有多个数据源的配置,那么就需要配置此项 -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

</beans>

jdbc.properties

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql:///test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
db.username=root
db.password=root

mappers

OrdersMapper.java

package com.hardes.mappers;

import com.hardes.pojos.OrdersExt;

import java.util.List;

public interface OrdersMapper {

    List<OrdersExt> findOrdersAndUsersByOid(int i);

}

OrdersMapper.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">
<!--
    namespace命名空间,作用就是对sql进行分类化管理,将sql隔离
    注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace为对应的mapper接口地址
-->
<mapper namespace="com.hardes.mappers.OrdersMapper">


    <!--一对一映射,还用resultType-->
    <select id="findOrdersAndUsersByOid" parameterType="int" resultType="com.hardes.pojos.OrdersExt">
        SELECT *

        FROM users,orders WHERE  orders.id=#{oid} AND orders.user_id= users.id
    </select>


</mapper>

UsersMapper.java

package com.hardes.mappers;

import com.hardes.pojos.Users;

import java.util.List;

public interface UsersMapper {

    List<Users> findOrdersAndUsersByOid1(int id);
}

UsersMapper.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">
<!--
    namespace命名空间,作用就是对sql进行分类化管理,将sql隔离
    注意:使用mapper代理方法开发,namespace有特殊重要的作用,namespace为对应的mapper接口地址
-->
<mapper namespace="com.hardes.mappers.UsersMapper">

    <resultMap id="findOrdersAndUsersReM" type="com.hardes.pojos.Users">
        <id column="uid" property="id"/>
        <result column="username" property="username"/>
        <result column="sex" property="sex"/>


        <association property="orders" javaType="com.hardes.pojos.Orders">
            <id column="oid" property="id"/>
            <result column="number" property="number"/>
            <result column="user_id" property="userId"/>
            <result column="time"   property="time"/>
        </association>
    </resultMap>

    <select id="findOrdersAndUsersByOid1" parameterType="int" resultMap="findOrdersAndUsersReM">
        SELECT
            users.id uid,
            users.username,
            users.sex,
            orders.id oid,
            orders.number,
            orders.user_id,
            orders.time

         FROM users,orders WHERE  users.id=#{id} AND users.id=orders.user_id
    </select>

</mapper>

7, pojos(Items 和detail_list类没有涉及,没有放)

Users.java

package com.hardes.pojos;

import java.util.Date;
import java.util.List;

public class Users {
    private int id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;
    //private Orders orders;
    //订单信息集合
   // private List<Orders> ordersList;



    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                ", address='" + address + '\'' +
                '}';
    }
}

Orders.java

package com.hardes.pojos;

import java.util.Date;
import java.util.List;


public class Orders {
    private Integer oid;
    private Integer user_id;
    private String number;
    private Date time;
    private String note;
   // private Users users;
    
    //订单明细集合
   // private List<Orders_detail> detailList;


    public Integer getOid() {
        return oid;
    }

    public void setOid(Integer oid) {
        this.oid = oid;
    }

    public Integer getUser_id() {
        return user_id;
    }

    public void setUser_id(Integer user_id) {
        this.user_id = user_id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    @Override
    public String toString() {
        return "Orders{" +
                "oid=" + oid +
                ", user_d=" + user_id +
                ", number='" + number + '\'' +
                ", time=" + time +
                ", note='" + note + '\'' +
                '}';
    }
}

Orders.Ext.java

package com.hardes.pojos;


import java.util.Date;

public class OrdersExt extends Orders {
    private String username;
    private Date birthday;
    private char sex;
    private String address;



    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }



    @Override
    public String toString() {
        return "OrdersExt{" +
                "username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                ", "+super.toString()+

                '}';
    }
}

8, 测试代码

package com.hardes;

import com.hardes.mappers.OrdersMapper;
import com.hardes.pojos.OrdersExt;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestUsers {
    @Test
    public void userTest(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
        /**
         * 使用resultType作映射,查询订单orders 并关联users的信息
         */
        OrdersMapper ordersmapper= (OrdersMapper) ac.getBean("ordersMapper");

        List<OrdersExt> list = ordersmapper.findOrdersAndUsersByOid(2);

        System.out.println(list);

    }
}

测试结果

[OrdersExt{username='Tom', birthday=Sun Oct 06 08:00:00 SGT 2019, sex=M, address='Jurong East', Orders{oid=null, user_d=1, number='2000', time=Mon Oct 07 21:47:26 SGT 2019, note='bread'}}]

9, 遇到问题

Orders{oid=null, 这里的值一直为空,说明数据库table的列明与实体类的属性的名字不一样,
透过大神的博客才明白:

查询出来的结果的列名需要对应我们编写的输出映射类型中的属性名,如果不匹配,则不能完成映射,那么查询出来的结果也不能如愿的放入对应的对象中去

resultType和resultMap

在这里插入图片描述

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:书香水墨 设计师:CSDN官方博客 返回首页

打赏作者

Hardison_C

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值