Mybatis表关联一对一

Posted 互联网IT信息

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis表关联一对一相关的知识,希望对你有一定的参考价值。


1Mybatis表关联一对一简介 

   此章节是讲解两个具备一对一关系的实体,在mybatis中如何配置映射文件,如何处理这个一对一的关系。

2Mybatis一对一的编码核心步骤 

1)环境前期准备

2)创建基于maven的工程MyBatis

3)创建持久化的实体类Course和Catalog,

两个实体一对一的关系,一个课程属于一个目录分类

4)配置数据库连接信息configure.xml

5)配置mybatis的sql语句,在配置文件onetoone.xml中

此配置文件主要涵盖一对一的关系映射,和基于这个关系的查询

6)创建测试类TestOneToOne

7)测试结果展示

3Mybatis一对一编码之:环境前期准备 

第一步:准备开发工具

Eclipse Neon 4.6.0

JDK 1.8

第二步:准备数据库:

1)     创建mysql数据实例:template

2)     创建表course和catalog,含有如下字段:

course表:

id:int(11)类型

coursename:varchar(45)类型

catalogid:int(11)类型

catalog表:

id:int(11)类型

catalogname:varchar(45)类型

第三步:往数据库中初始化数据:

  course表初始化:

INSERT INTO `course` VALUES ('3', 'course3', '3');

     catalog表初始化:

INSERT INTO `catalog` VALUES ('3', 'catalog3');

4Mybatis一对一编码之:创建基于maven的工程MyBatis 

第一步:基于Maven创建工程MyBatis

  第二步:配置工程依赖的jar包,在pom.xml中:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

 

  <groupId>com.test</groupId>

  <artifactId>MyBatis</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>jar</packaging>

 

  <name>MyBatis</name>

  <url>http://maven.apache.org</url>

 

   <properties>

           <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

           <spring.version>4.1.4.RELEASE</spring.version>

     </properties>

     <dependencies>

           <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-context</artifactId>

                <version>${spring.version}</version>

           </dependency>

           <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-aop</artifactId>

                <version>${spring.version}</version>

           </dependency>

           <dependency>

                <groupId>javax.servlet</groupId>

                <artifactId>jstl</artifactId>

                <version>1.2</version>

           </dependency>

           <dependency>

                <groupId>commons-logging</groupId>

                <artifactId>commons-logging</artifactId>

                <version>1.1.3</version>

           </dependency>

           <dependency>

                <groupId>commons-dbcp</groupId>

                <artifactId>commons-dbcp</artifactId>

                <version>1.4</version>

           </dependency>

           <dependency>

                <groupId>commons-pool</groupId>

                <artifactId>commons-pool</artifactId>

                <version>1.6</version>

           </dependency>

           <dependency>

                <groupId>org.codehaus.jackson</groupId>

                <artifactId>jackson-mapper-asl</artifactId>

                <version>1.9.13</version>

           </dependency>

           <dependency>

                <groupId>com.fasterxml.jackson.core</groupId>

                <artifactId>jackson-annotations</artifactId>

                <version>2.6.1</version>

           </dependency>

           <dependency>

                <groupId>com.fasterxml.jackson.core</groupId>

                <artifactId>jackson-core</artifactId>

                <version>2.6.1</version>

           </dependency>

           <dependency>

                <groupId>com.fasterxml.jackson.core</groupId>

                <artifactId>jackson-databind</artifactId>

                <version>2.6.1</version>

           </dependency>

          

           <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-orm</artifactId>

                <version>${spring.version}</version>

           </dependency>

           <dependency>

                <groupId>org.mybatis</groupId>

                <artifactId>mybatis-spring</artifactId>

                <version>1.2.3</version>

           </dependency>

           <dependency>

                <groupId>mysql</groupId>

                <artifactId>mysql-connector-java</artifactId>

                <version>5.1.36</version>

           </dependency>

           <dependency>

                <groupId>org.mybatis</groupId>

                <artifactId>mybatis</artifactId>

                <version>3.3.0</version>

           </dependency>

           <dependency>

                <groupId>c3p0</groupId>

                <artifactId>c3p0</artifactId>

                <version>0.9.1.2</version>

           </dependency>

 

 

           <dependency>

                <groupId>log4j</groupId>

                <artifactId>log4j</artifactId>

                <version>1.2.17</version>

           </dependency>

     </dependencies>

</project>

第三步:按照如下工程结构创建相关文件:

5Mybatis一对一编码之:创建持久化的实体类Course和Catalog 

第一步:创建包:com.test.model

第二步:在该包下创建Course和Catalog

Course类:

package com.test.model;

 

public class Course {

 

    private long id;

   

    private String coursename;

   

    private Catalog catalog;

   

    public long getId() {

       return id;

    }

 

    public void setId(long id) {

       this.id = id;

    }

 

 

    public String getCoursename() {

       return coursename;

    }

 

    public void setCoursename(String coursename) {

       this.coursename = coursename;

    }

 

    public Catalog getCatalog() {

       return catalog;

    }

 

    public void setCatalog(Catalog catalog) {

       this.catalog = catalog;

    }

}



Catalog类



package com.test.model;

 

public class Catalog {

 

    private long id;

   

    private String catalogname;

 

    public long getId() {

       return id;

    }

 

    public void setId(long id) {

       this.id = id;

    }

 

    public String getCatalogname() {

       return catalogname;

    }

 

    public void setCatalogname(String catalogname) {

       this.catalogname = catalogname;

    }

   

   

}

6一对一编码之:配置数据库连接信息configure.xml

第一步:创建文件夹src/main/resources

第二步: 创建包:config.ch03

第三步:在该包下创建配置文件

补充:该配置文件的核心节点介绍如下:

typeAliases节点:类型命名,作用是为java类命别名,从而减少后续应用别名的冗余;

environments节点:配置mybatis连接的基础环境的。比如:事务管理器,数据库连接信息等;

mappers节点:映射器,配置mybatis的映射文件的位置信息等

<?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>

       <typeAlias alias="Course" type="com.test.model.Course" />

       <typeAlias alias="Catalog" type="com.test.model.Catalog" />

    </typeAliases>

   

    <environments default="development">

       <environment id="development">

           <transactionManager type="JDBC" />

           <dataSource type="POOLED">

              <property name="driver" value="com.mysql.jdbc.Driver" />

              <property name="url" value="jdbc:mysql://127.0.0.1:3306/template" />

              <property name="username" value="root" />

              <property name="password" value="123456" />

           </dataSource>

       </environment>

    </environments>

 

    <mappers>

       <mapper resource="com/test/ch03/onetoone.xml" />

    </mappers>

</configuration>

7Mybatis一对一编码之:配置mybatis的sql语句,在配置文件onetoone.xml中 

第一步:创建包:com.test.ch03

第二步:在该包下创建配置文件

补充:association节点就是配置一对一关系的

<?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.test.ch03.CourseMapper">

 

    <resultMap type="Course" id="resultCourseMap">

       <result property="id" column="id" />

       <result property="coursename" column="coursename" />

       <association property="catalog" javaType="Catalog"> 

            <id column="id" property="id" /> 

            <result column="catalogname" property="catalogname" /> 

        </association> 

    </resultMap>

   

    <select id="getCourse" resultMap="resultCourseMap" parameterType="int">

       SELECT c.coursename,ct.catalogname

       FROM  course c, catalog ct

       WHERE c.catalogid=ct.id AND c.id=#{id}

    </select>

   

</mapper>

8Mybatis一对一编码之:编写测试类 

在包:com.test.ch03下创建测试类:

TestOneToOne类

package com.test.ch03;

 

import java.io.Reader;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;

 

import com.test.model.Catalog;

import com.test.model.Course;

 

public class TestOneToOne {

 

    private static SqlSessionFactory sqlSessionFactory;

    private static Reader reader;

 

    static {

       try {

           reader = Resources.getResourceAsReader

("config/ch03/Configure.xml");

           sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

       } catch (Exception e) {

           e.printStackTrace();

       }

    }

 

    public static void main(String[] args) {

       SqlSession session = sqlSessionFactory.openSession();

       try {

           Course c = session.selectOne("com.test.ch03.CourseMapper.getCourse", 3);

           System.out .println("coursename: " +  c.getCoursename());

          

           Catalog catalog = c.getCatalog();

           System.out .println("catalogname: " + catalog.getCatalogname());

 

       } finally {

           session.close();

       }

    }

 

}

9Mybatis一对一编码之:结果展示 

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).

log4j:WARN Please initialize the log4j system properly.

log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

coursename: course3

catalogname: catalog3

以上是关于Mybatis表关联一对一的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis高级篇 - 关联查询(一对多)

MyBatis_关联关系查询

mybatis一对一关联关系映射

mytabits表关联一对一(多对一?)

Mybatis关联查询一对一和一对多的实现

mybatis 一对一关联映射实例