一、实验目的:
掌握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.编写测试类表用控制
三、代码:
项目结构.png1.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();
}
}
四、运行结果
批次和用户1:1.png批次和产品1:n.png
输出全部.png
网友评论