[JAVAEE]實驗07:MyBatis關聯映射實踐

一、實驗目的:

掌握MyBatis的關聯映射(一對一、一對多、多對多)
實驗內容:
模擬用戶批量購買理財產品的業務。用戶(customer)一個批次(batch)可以購買多款理財產品(product)。
此業務邏輯涉及4張表:用戶表、批次表、批次明細表、理財產品表。
(1)查詢一個購買批次的信息以及創建該批次的用戶;
(2)在(1)的基礎上增加對該批次從屬的理財產品信息的查詢;
(3)查詢所有用戶以及用戶對應的批次訂單中所有理財產品的詳細信息。
實驗要求:
(1)提交源代碼和運行截圖。

二、設計:

用戶和批次是一對一:批次表中用外鍵引用用戶id
批次和理財產品是多對多:用batchdetail表明一一對應關係

表結構:
用戶(用戶表)
批次(批次表)
(批次明細表)
理財產品(理財產品表)

(1)查詢一個購買批次的信息以及創建該批次的用戶;
1.根據batchid查詢批次,內部嵌套(2)這是一對一
2.根據cusid查詢用戶

(2)在(1)的基礎上增加對該批次從屬的理財產品信息的查詢;
在2的基礎上增加調用理財產品查詢,根據batchid查詢產品
(在寫方法的時候是一對多)

(3)查詢所有用戶以及用戶對應的批次訂單中所有理財產品的詳細信息。
查詢所有
(多對多)

基本步驟:

  • 1.數據庫建立數據表
  • 2.創建po持久化類
  • 3.核心配置文件內部寫好映射表位置
  • 4.編寫映射表(普通sql,一對一,一對多,多對多)
  • 5.若映射表內使用了pojo類來打包結果集,則還需創建pojo類
  • 6.編寫操作接口Dao(名稱和映射相同)
  • 7.編寫控制類調用Dao
  • 8.編寫測試類表用控制

三、代碼:

1.Sql建表語句:

/*
SQLyog 企業版 - MySQL GUI v8.14 
MySQL - 5.6.24 : Database - mybatis_test
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis_test` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */;

USE `mybatis_test`;

/*Table structure for table `batch` */

DROP TABLE IF EXISTS `batch`;

CREATE TABLE `batch` (
  `batch_id` int(11) NOT NULL AUTO_INCREMENT,
  `cus_id` int(11) NOT NULL COMMENT '創建批次用戶id',
  `number` varchar(32) NOT NULL COMMENT '批次編碼',
  `createtime` datetime NOT NULL COMMENT '創建批次時間',
  `note` varchar(100) DEFAULT NULL COMMENT '備註',
  PRIMARY KEY (`batch_id`),
  KEY `FK_batch_1` (`cus_id`),
  CONSTRAINT `FK_batch_id` FOREIGN KEY (`cus_id`) REFERENCES `customer` (`cus_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

/*Data for the table `batch` */

insert  into `batch`(`batch_id`,`cus_id`,`number`,`createtime`,`note`) values (1,1,'00001','2017-07-22 00:00:00','首次購買'),(2,3,'00002','2017-03-11 00:00:00','委託購買');

/*Table structure for table `batchdetail` */

DROP TABLE IF EXISTS `batchdetail`;

CREATE TABLE `batchdetail` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `batch_id` int(11) NOT NULL COMMENT '批次id',
  `product_id` int(11) NOT NULL COMMENT '理財產品id',
  `product_num` int(11) DEFAULT NULL COMMENT '理財產品購買數量',
  PRIMARY KEY (`id`),
  KEY `FK_batchdetail_1` (`batch_id`),
  KEY `FK_batchdetail_2` (`product_id`),
  CONSTRAINT `FK_batchdetai_1` FOREIGN KEY (`batch_id`) REFERENCES `batch` (`batch_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `FK_batchdetai_2` FOREIGN KEY (`product_id`) REFERENCES `finacial_products` (`product_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

/*Data for the table `batchdetail` */

insert  into `batchdetail`(`id`,`batch_id`,`product_id`,`product_num`) values (1,1,1,2),(2,1,2,1),(3,1,3,1),(4,2,1,2),(5,2,2,1);

/*Table structure for table `customer` */

DROP TABLE IF EXISTS `customer`;

CREATE TABLE `customer` (
  `cus_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用戶名稱',
  `acno` varchar(32) DEFAULT NULL COMMENT '卡號',
  `gender` varchar(4) DEFAULT NULL COMMENT '性別',
  `phone` varchar(256) DEFAULT NULL COMMENT '電話',
  PRIMARY KEY (`cus_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

/*Data for the table `customer` */

insert  into `customer`(`cus_id`,`username`,`acno`,`gender`,`phone`) values (1,'劉雲','6228286666666','男','13800000000'),(2,'李健','622848111111','男','13811111111'),(3,'張麗麗','622848333333','女','13822222222');

/*Table structure for table `finacial_products` */

DROP TABLE IF EXISTS `finacial_products`;

CREATE TABLE `finacial_products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL COMMENT '理財產品名稱',
  `price` float(10,1) NOT NULL COMMENT '理財產品定價',
  `detail` text COMMENT '理財產品描述',
  `pic` varchar(64) DEFAULT NULL COMMENT '理財產品圖片',
  `invasttime` datetime NOT NULL COMMENT '理財產品收益日期',
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

/*Data for the table `finacial_products` */

insert  into `finacial_products`(`product_id`,`name`,`price`,`detail`,`pic`,`invasttime`) values (1,'一起富',5000.0,'投資少,風險小','img001','2017-06-21 00:00:00'),(2,'惠薪富',10000.0,'收益穩健','img002','2017-05-03 00:00:00'),(3,'安富尊容',15000.0,'年收益率提升5%','img003','2017-07-18 00:00:00'),(4,'富津利',2000.0,'企劃收益率','img004','2017-04-11 00:00:00');

2.配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 指定需要掃描的包(包括子包),使註解生效 -->  
    <context:component-scan base-package="com.dao"/>
    <context:component-scan base-package="com.controller"/>
    <!-- 配置數據源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis_test?characterEncoding=utf8" />
            <property name="username" value="root" />
            <property name="password" value="363316495" />
            <!-- 最大連接數 -->
            <property name="maxTotal" value="30"/>
            <!-- 最大空閒連接數 -->
            <property name="maxIdle" value="10"/>
            <!-- 初始化連接數 -->
            <property name="initialSize" value="5"/>
    </bean>
    
    
    <!-- 添加事務支持 -->
    <bean id="txManager"   
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
        <property name="dataSource" ref="dataSource" />   
    </bean> 
    <!-- 開啓事務註解-->
    <tx:annotation-driven transaction-manager="txManager" />
    
    
    
    
    <!-- 配置MyBatis工廠,同時指定數據源,並與MyBatis完美整合 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- configLocation的屬性值爲MyBatis的核心配置文件 -->
        <property name="configLocation" value="classpath:com/mybatis/mybatis-config.xml"/>
    </bean>  
    
    
    <!--Mapper代理開發,使用Spring自動掃描MyBatis的接口並裝配
    (Spring將指定包中所有被@Mapper註解標註的接口自動裝配爲MyBatis的映射接口)  --> 
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- mybatis-spring組件的掃描器 -->
        <property name="basePackage" value="com.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
     </bean>
</beans>

3.持久化類po

Batch.java
package com.po;

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

public class Batch {
    private int id;
    private String number;
    private Date createtime;
    private String note;
    
    //與顧客是一對一
    private Customer customer;
    
    //與訂單是多對多
    private List<Product> products;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public Customer getCustomer() {
        return customer;
    }
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public Date getCreatetime() {
        return createtime;
    }
    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note;
    }
    public List<Product> getProducts() {
        return products;
    }
    public void setProducts(List<Product> products) {
        this.products = products;
    }
    @Override
    public String toString() {
        return "Batch [id=" + id + ", createtime=" + createtime
                + ", note=" + note + "]";
    }
}

Customer.java

package com.po;
public class Customer {
    private int id;
    private String username;
    private String acno;
    private String gender;
    private String phone;
    
    
    
    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 getAcno() {
        return acno;
    }
    public void setAcno(String acno) {
        this.acno = acno;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    
    @Override
    public String toString() {
        return "Customer [id=" + id + ", username=" + username + ", acno=" + acno + ", gender=" + gender + ", phone="
                + phone + "]";
    }
    
}

Product.java

package com.po;

import java.util.Date;
import java.util.List;
//對應表finacial_products
public class Product {
    
    private int product_id;
    private String name;
    private int price;
    private String detail;
    private String pic;
    private Date invasttime;
    
    //與batch是多對多
    private List<Batch> Batch;
    
    public int getProduct_id() {
        return product_id;
    }
    public void setId(int product_id) {
        this.product_id = product_id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail;
    }
    public String getPic() {
        return pic;
    }
    public void setPic(String pic) {
        this.pic = pic;
    }
    public Date getInvasttime() {
        return invasttime;
    }
    public void setInvasttime(Date invasttime) {
        this.invasttime = invasttime;
    }
    
    
    public List<Batch> getOrders() {
        return Batch;
    }
    public void setOrders(List<Batch> Batch) {
        this.Batch = Batch;
    }
    
    
    @Override
    public String toString() {
        return "Product product_id=" + product_id + ", name=" + name + ", price=" + price + ", detail=" + detail + ", pic=" + pic
                + ", invasttime=" + invasttime + "]";
    }
    
}

4.mybatis(非核心映射文件是sql和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>
    <!-- 在使用MyBatis嵌套查詢方式進行關聯查詢時,使用MyBatis的延遲加載在一定程度可以提高查詢效率 -->
    <settings>
        <!-- 打開延遲加載的開關 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 將積極加載改爲按需加載 -->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

     <mappers><!-- 映射器,告訴 MyBatis到哪裏去找映射文件-->
        <mapper resource="com/mybatis/CustomerMapper.xml"/>
        <mapper resource="com/mybatis/BatchMapper.xml"/>
       
       
    </mappers>
</configuration>

BatchMapper.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.dao.BatchDao">
    
    
    <!-- 一、一對一 根據batchid查詢:第三種方法(使用POJO存儲結果) -->
    <!-- 先找batch再找批次對應的用戶 -->
    <select id="selectBatchById" parameterType="Integer" resultType="com.pojo.SelectBatchById">
        select bat.*,cus.cus_id
        from batch bat, customer cus
        where bat.cus_id = cus.cus_id and bat.batch_id=#{id}
    </select>
    
    
    <!--二、 一對多 根據batchid查詢用戶及其關聯的訂單信息:第三種方法(使用POJO存儲結果) -->
    <!-- 注意這裏的sql語句,一定要寫規範! 我在from這裏多寫了一個batch的表就導致輸出的結果是原來的兩倍-->
    <select id="selectBatchProductById" parameterType="Integer" resultType="com.pojo.SelectBatchProductById">
        select pro.product_id,pro.name
        from  finacial_products pro,batchdetail detail 
        where detail.product_id = pro.product_id and detail.batch_id=#{id}
    </select>
    
    
    <!--三、查詢所有用戶以及用戶對應的批次訂單中所有理財產品的詳細信息  -->
    <select id="selectallBatchAndProducts"   resultType="com.pojo.allBatchAndProducts">
        select cus.cus_id,bat.batch_id,pro.product_id
        from customer cus,batch bat,batchdetail detail,finacial_products pro
        where detail.batch_id = bat.batch_id 
        and detail.product_id = pro.product_id
        and bat.cus_id = cus.cus_id 
    </select>
    
    
    
</mapper>

CustomerMapper.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.dao.CustomerDao">

<!-- sql與xml的映射文件 -->
    <select id="selectCustomerByid" parameterType="Integer" resultType="com.po.Customer">
        select * from customer where cus_id=#{id}
    </select>
</mapper>

5.pojo結果集(最方便)

allBatchAndProducts.java

package com.pojo;

public class allBatchAndProducts {
    String cus_id;
    String batch_id;
    String product_id;
    
    public String getcus_id() {
        return cus_id;
    }
    public void setcus_id(String cus_id) {
        this.cus_id = cus_id;
    }
    
    
    
    public String getGender() {
        return product_id;
    }
    public void setbatch_id(String batch_id) {
        this.batch_id = batch_id;
    }
    
    
    
    public String getproduct_id() {
        return product_id;
    }
    public void setproduct_id(String product_id) {
        this.product_id = product_id;
    }
    
    @Override
    public String toString() {
        return "Customer [cus_id=" + cus_id + ", batch_id=" + batch_id + ", product_id=" + product_id+ "]";
    }
}

SelectBatchById.java

package com.pojo;

import java.util.Date;


public class SelectBatchById {
    private int id;
    private String number;
    private Date createtime;
    private String note;
    
    //與顧客是一對一
    private String cus_id;
    
    
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public Date getCreatetime() {
        return createtime;
    }
    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note;
    }
    
    
    
    public String getCusid() {
        return cus_id;
    }
    public void setCusid(String cusid) {
        this.cus_id = cusid;
    }
    
    
    @Override
    public String toString() {
        return "Batch [id=" + id + ", createtime=" + createtime
                + ", note=" + note + ", cus_id=" + cus_id +"]";
    }
    
}

SelectBatchProductById.java

package com.pojo;

public class SelectBatchProductById {

    String  product_id;
    String  name;
    
    public String getproduct_id() {
        return product_id;
    }
    public void setproduct_id(String product_id) {
        this.product_id = product_id;
    }
    
    
    public String getname() {
        return name;
    }
    public void setname(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "Batch [product_id=" + product_id + ", name=" + name +"]";
    }
    
    
}

6.Dao 數據操作類
BatchDao.java

package com.dao;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import com.pojo.SelectBatchById;
import com.pojo.SelectBatchProductById;
import com.pojo.allBatchAndProducts;

//說句操縱接口(要和mapper一一對應)

@Repository("BatchDao")
@Mapper
public interface BatchDao {
    
    public SelectBatchById selectBatchById(Integer id);
    
    //一對多
    public List<SelectBatchProductById> selectBatchProductById(Integer id);
    
    //多對多
    public  List<allBatchAndProducts> selectallBatchAndProducts() ;
        
}

CustomerDao.java

package com.dao;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import com.po.Customer;

@Repository("CustomerDao")
@Mapper


public interface CustomerDao {
    public Customer selectCustomerByid(Integer i);
}

7.控制和測試類

(名字我複製的,可以隨意改)
OneToOneController.java

package com.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.dao.BatchDao;

import com.pojo.SelectBatchById;
import com.pojo.SelectBatchProductById;
import com.pojo.allBatchAndProducts;

@Controller("oneToOneController")
public class OneToOneController {
    @Autowired
    private BatchDao batchDao;
    public void test() {
        
        //一對一
        SelectBatchById p = batchDao.selectBatchById(1);
        System.out.println("查詢一個購買批次的信息以及創建該批次的用戶:");
        System.out.println(p);
        
        //一對多
        List<SelectBatchProductById> p1 = batchDao.selectBatchProductById(1);
        System.out.println("增加對該批次從屬的理財產品信息的查詢:");
        for (SelectBatchProductById ppp : p1) {
            System.out.println(ppp);
        }

        
        //多對多
        System.out.println("查詢所有用戶以及用戶對應的批次訂單中所有理財產品的詳細信息:");
        List<allBatchAndProducts> bat = batchDao.selectallBatchAndProducts();
        for (allBatchAndProducts i : bat) {
            System.out.println(i);
        }
        
        
    }
}

TestOneToOne.java測試

package com.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestOneToOne {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        OneToOneController oto = (OneToOneController)appCon.getBean("oneToOneController");
        oto.test();
    }
}

四、運行結果



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章