一草冈、實(shí)驗(yàn)?zāi)康模?/h2>
掌握MyBatis的關(guān)聯(lián)映射(一對(duì)一棺蛛、一對(duì)多藏畅、多對(duì)多)
實(shí)驗(yàn)內(nèi)容:
模擬用戶(hù)批量購(gòu)買(mǎi)理財(cái)產(chǎn)品的業(yè)務(wù)敷硅。用戶(hù)(customer)一個(gè)批次(batch)可以購(gòu)買(mǎi)多款理財(cái)產(chǎn)品(product)。
此業(yè)務(wù)邏輯涉及4張表:用戶(hù)表愉阎、批次表绞蹦、批次明細(xì)表、理財(cái)產(chǎn)品表榜旦。
(1)查詢(xún)一個(gè)購(gòu)買(mǎi)批次的信息以及創(chuàng)建該批次的用戶(hù)幽七;
(2)在(1)的基礎(chǔ)上增加對(duì)該批次從屬的理財(cái)產(chǎn)品信息的查詢(xún);
(3)查詢(xún)所有用戶(hù)以及用戶(hù)對(duì)應(yīng)的批次訂單中所有理財(cái)產(chǎn)品的詳細(xì)信息溅呢。
實(shí)驗(yàn)要求:
(1)提交源代碼和運(yùn)行截圖澡屡。
二、設(shè)計(jì):
用戶(hù)和批次是一對(duì)一:批次表中用外鍵引用用戶(hù)id
批次和理財(cái)產(chǎn)品是多對(duì)多:用batchdetail表明一一對(duì)應(yīng)關(guān)系
表結(jié)構(gòu):
用戶(hù)(用戶(hù)表)
批次(批次表)
(批次明細(xì)表)
理財(cái)產(chǎn)品(理財(cái)產(chǎn)品表)
(1)查詢(xún)一個(gè)購(gòu)買(mǎi)批次的信息以及創(chuàng)建該批次的用戶(hù)咐旧;
1.根據(jù)batchid查詢(xún)批次驶鹉,內(nèi)部嵌套(2)這是一對(duì)一
2.根據(jù)cusid查詢(xún)用戶(hù)
(2)在(1)的基礎(chǔ)上增加對(duì)該批次從屬的理財(cái)產(chǎn)品信息的查詢(xún);
在2的基礎(chǔ)上增加調(diào)用理財(cái)產(chǎn)品查詢(xún),根據(jù)batchid查詢(xún)產(chǎn)品
(在寫(xiě)方法的時(shí)候是一對(duì)多)
(3)查詢(xún)所有用戶(hù)以及用戶(hù)對(duì)應(yīng)的批次訂單中所有理財(cái)產(chǎn)品的詳細(xì)信息铣墨。
查詢(xún)所有
(多對(duì)多)
基本步驟:
- 1.數(shù)據(jù)庫(kù)建立數(shù)據(jù)表
- 2.創(chuàng)建po持久化類(lèi)
- 3.核心配置文件內(nèi)部寫(xiě)好映射表位置
- 4.編寫(xiě)映射表(普通sql室埋,一對(duì)一,一對(duì)多伊约,多對(duì)多)
- 5.若映射表內(nèi)使用了pojo類(lèi)來(lái)打包結(jié)果集姚淆,則還需創(chuàng)建pojo類(lèi)
- 6.編寫(xiě)操作接口Dao(名稱(chēng)和映射相同)
- 7.編寫(xiě)控制類(lèi)調(diào)用Dao
- 8.編寫(xiě)測(cè)試類(lèi)表用控制
三、代碼:
1.Sql建表語(yǔ)句:
/*
SQLyog 企業(yè)版 - 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 '創(chuàng)建批次用戶(hù)id',
`number` varchar(32) NOT NULL COMMENT '批次編碼',
`createtime` datetime NOT NULL COMMENT '創(chuàng)建批次時(shí)間',
`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','首次購(gòu)買(mǎi)'),(2,3,'00002','2017-03-11 00:00:00','委托購(gòu)買(mǎi)');
/*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 '理財(cái)產(chǎn)品id',
`product_num` int(11) DEFAULT NULL COMMENT '理財(cái)產(chǎn)品購(gòu)買(mǎi)數(shù)量',
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 '用戶(hù)名稱(chēng)',
`acno` varchar(32) DEFAULT NULL COMMENT '卡號(hào)',
`gender` varchar(4) DEFAULT NULL COMMENT '性別',
`phone` varchar(256) DEFAULT NULL COMMENT '電話(huà)',
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 '理財(cái)產(chǎn)品名稱(chēng)',
`price` float(10,1) NOT NULL COMMENT '理財(cái)產(chǎn)品定價(jià)',
`detail` text COMMENT '理財(cái)產(chǎn)品描述',
`pic` varchar(64) DEFAULT NULL COMMENT '理財(cái)產(chǎn)品圖片',
`invasttime` datetime NOT NULL COMMENT '理財(cái)產(chǎn)品收益日期',
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,'投資少屡律,風(fēng)險(xiǎn)小','img001','2017-06-21 00:00:00'),(2,'惠薪富',10000.0,'收益穩(wěn)健','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"/>
<!-- 配置數(shù)據(jù)源 -->
<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" />
<!-- 最大連接數(shù) -->
<property name="maxTotal" value="30"/>
<!-- 最大空閑連接數(shù) -->
<property name="maxIdle" value="10"/>
<!-- 初始化連接數(shù) -->
<property name="initialSize" value="5"/>
</bean>
<!-- 添加事務(wù)支持 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 開(kāi)啟事務(wù)注解-->
<tx:annotation-driven transaction-manager="txManager" />
<!-- 配置MyBatis工廠,同時(shí)指定數(shù)據(jù)源超埋,并與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代理開(kāi)發(fā)上忍,使用Spring自動(dòng)掃描MyBatis的接口并裝配
(Spring將指定包中所有被@Mapper注解標(biāo)注的接口自動(dòng)裝配為MyBatis的映射接口) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- mybatis-spring組件的掃描器 -->
<property name="basePackage" value="com.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
</beans>
3.持久化類(lèi)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;
//與顧客是一對(duì)一
private Customer customer;
//與訂單是多對(duì)多
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;
//對(duì)應(yīng)表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是多對(duì)多
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嵌套查詢(xún)方式進(jìn)行關(guān)聯(lián)查詢(xún)時(shí)骤肛,使用MyBatis的延遲加載在一定程度可以提高查詢(xún)效率 -->
<settings>
<!-- 打開(kāi)延遲加載的開(kāi)關(guān) -->
<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">
<!-- 一窍蓝、一對(duì)一 根據(jù)batchid查詢(xún):第三種方法(使用POJO存儲(chǔ)結(jié)果) -->
<!-- 先找batch再找批次對(duì)應(yīng)的用戶(hù) -->
<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>
<!--二腋颠、 一對(duì)多 根據(jù)batchid查詢(xún)用戶(hù)及其關(guān)聯(lián)的訂單信息:第三種方法(使用POJO存儲(chǔ)結(jié)果) -->
<!-- 注意這里的sql語(yǔ)句,一定要寫(xiě)規(guī)范吓笙! 我在from這里多寫(xiě)了一個(gè)batch的表就導(dǎo)致輸出的結(jié)果是原來(lái)的兩倍-->
<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>
<!--三淑玫、查詢(xún)所有用戶(hù)以及用戶(hù)對(duì)應(yīng)的批次訂單中所有理財(cái)產(chǎn)品的詳細(xì)信息 -->
<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">
<!--綁定數(shù)據(jù)操作接口 -->
<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結(jié)果集(最方便)
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;
//與顧客是一對(duì)一
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 數(shù)據(jù)操作類(lèi)
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;
//說(shuō)句操縱接口(要和mapper一一對(duì)應(yīng))
@Repository("BatchDao")
@Mapper
public interface BatchDao {
public SelectBatchById selectBatchById(Integer id);
//一對(duì)多
public List<SelectBatchProductById> selectBatchProductById(Integer id);
//多對(duì)多
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.控制和測(cè)試類(lèi)
(名字我復(fù)制的,可以隨意改)
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() {
//一對(duì)一
SelectBatchById p = batchDao.selectBatchById(1);
System.out.println("查詢(xún)一個(gè)購(gòu)買(mǎi)批次的信息以及創(chuàng)建該批次的用戶(hù):");
System.out.println(p);
//一對(duì)多
List<SelectBatchProductById> p1 = batchDao.selectBatchProductById(1);
System.out.println("增加對(duì)該批次從屬的理財(cái)產(chǎn)品信息的查詢(xún):");
for (SelectBatchProductById ppp : p1) {
System.out.println(ppp);
}
//多對(duì)多
System.out.println("查詢(xún)所有用戶(hù)以及用戶(hù)對(duì)應(yīng)的批次訂單中所有理財(cái)產(chǎn)品的詳細(xì)信息:");
List<allBatchAndProducts> bat = batchDao.selectallBatchAndProducts();
for (allBatchAndProducts i : bat) {
System.out.println(i);
}
}
}
TestOneToOne.java測(cè)試
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();
}
}