1. 程式人生 > >Mybatis一對多的關係

Mybatis一對多的關係

前言:本專案是使用idea進行開發,資料庫使用的是Mysql。
province(一)----------city(多)
在這裡插入圖片描述
在這裡插入圖片描述
1.搭建maven專案,引入mybatis需要的依賴
預設沒有java、resources、test等資料夾,習慣性建立這幾個資料夾,建立資料夾的時候注意標記資料夾的用途(不然編譯器無法識別,無法編譯程式碼)
pom.xml(注意要將實體包下面的xml檔案設定可編譯)

<?xml version="1.0" encoding="UTF-8"?>

<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>Mybatis_03</groupId> <artifactId>Mybatis_03</artifactId> <version>1.0-SNAPSHOT</
version
>
<packaging>war</packaging> <name>Mybatis_03 Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <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> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--引入Mybatis依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <!--引入MySql依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.43</version> </dependency> </dependencies> <build> <!--設定java目錄下的com.zs.entity的對映檔案作為資原始檔編譯--> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> <finalName>Mybatis_03</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</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> </plugins> </pluginManagement> </build> </project>

2.專案模組圖:
在這裡插入圖片描述
3.在resources目錄下新建mybatis的核心配置檔案mybatis-config.xml
mybatis-config.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>
    <!--給com.zs.entity包取別名-->
    <typeAliases>
        <package name="com.zs.entity"/>
    </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://localhost:3306/zs?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="1234" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/zs/entity/City.xml"></mapper>
        <mapper resource="com/zs/entity/Province.xml"></mapper>
    </mappers>
</configuration>

4.建立與資料庫對應的實體包,包下建立類與對應的xml檔案(這裡沒有使用介面呼叫方法,是使用xml檔案呼叫方法)
Province.java

package com.zs.entity;

import java.util.List;

/**
 * @author 小思
 * @PackageName:com.zs.entity
 * @ClassName: Province
 * @Description:對應資料庫Province表的實體類
 * @date 2018/10/31 16:32
 */
public class Province {
    private Integer pid;
    private String pname;
    private List<city> cities;

    public Province() {
    }

    public Province(Integer pid) {
        this.pid = pid;
    }

    public Province(String pname) {
        this.pname = pname;
    }

    public Province(Integer pid, String pname) {
        this.pid = pid;
        this.pname = pname;
    }

    public Province(Integer pid, String pname, List<city> cities) {
        this.pid = pid;
        this.pname = pname;
        this.cities = cities;
    }

    public Integer getPid() {
        return pid;
    }

    public void setPid(Integer pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    public List<city> getCities() {
        return cities;
    }

    public void setCities(List<city> cities) {
        this.cities = cities;
    }
}

city.java

package com.zs.entity;

/**
 * @author 小思
 * @PackageName:com.zs.entity
 * @ClassName: city
 * @Description:對應資料庫City表的實體類
 * @date 2018/10/31 16:33
 */
public class city {
    private Integer cid;//城市的Id
    private String cname;//城市的名稱
    private Province province;//城市所對應的省份

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public Province getProvince() {
        return province;
    }

    public void setProvince(Province province) {
        this.province = province;
    }

    public city() {
    }

    public city(Integer cid) {
        this.cid = cid;
    }

    public city(String cname) {
        this.cname = cname;
    }

    public city(Integer cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }

    public city(Integer cid, String cname, Province province) {
        this.cid = cid;
        this.cname = cname;
        this.province = province;
    }

}

Province.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.zs.dao.ProvinceDao">
    <!--通過對映檔案的配置資訊,通過載入ProvinceDao介面找尋對應的方法-->
    <select id="getAllProvince" resultType="Province">
        select * from province
    </select>

    <!--根據省份的Id查詢城市-->
    <select id="findCityById" resultType="city" parameterType="int">
        select * from city where pid=#{pid}
    </select>

</mapper>

5.在test資料夾下新建com.zs.test資料夾,並且新建單元測試類TestOneToMany.java

package com.zs.test;

import com.zs.dao.ProvinceDao;
import com.zs.entity.city;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @author 小思
 * @PackageName:com.zs.test
 * @ClassName: TestOneToMany
 * @Description:
 * @date 2018/10/31 16:42
 */
@SuppressWarnings("unused")
public class TestOneToMany {
    SqlSessionFactory sessionFactory;
    SqlSession session;

    @Before
    public void before() {
        //從mybatis-config.xml mybatis的核心配置檔案中獲取SqlSessionFactory
        sessionFactory = new SqlSessionFactoryBuilder().build(getClass().getClassLoader().getResourceAsStream("mybatis-config.xml"));
        //通過工廠獲取SqlSession
        session = sessionFactory.openSession();
    }


    @Test
    public void testProvince() {
        // 對映器是一個你建立來繫結你對映的語句的介面,呼叫合理描述引數和返回值的介面來獲取相應的方法
        ProvinceDao pd = session.getMapper(ProvinceDao.class);

//        //查詢所有的省份
//        List<Province> list = pd.getAllProvince();
//        for (Province p : list) {
//            System.out.println(p.getPname());
//        }

        //根據省份的Id查詢城市
        List<city> c=pd.findCityById(1);
        for (city city : c) {
            System.out.println(city.getCname());
        }


    }

    @After
    public void after() {
        //提交session和關閉session(釋放無用資源)
        session.commit();
        session.close();
    }
}

6.測試時,取消註釋,執行測試類即可

說在最後的話:編寫實屬不易,若喜歡或者對你有幫助記得點贊+關注或者收藏哦~