您的位置:首页 > 其它

SSM整合框架之多对多查询

2018-11-25 13:16 302 查看

什么是SSM框架:
SSM框架就是Spring、SpringMVC、MyBatis三个框架的整合,是标准的MVC模式,将整个系统划分为表现层、Controller层、Service层、Dao层四层。使用SpringMVC负责请求的转发和视图管理,Spring实现业务对象管理,Mybatis作为数据对象的持久化引擎

简单介绍了下SSM,就直接上代码吧!

先引入jar包

pom.xml

<properties>
<!-- spring版本号 -->
<spring.version>4.0.2.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency> -->

<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>

<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>

<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>

<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>

<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- 上传组件包 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
</dependencies>

<build>
<finalName>maven01</finalName>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.8.v20150217</version>
<configuration>
<httpConnector>
<port>80</port>
</httpConnector>
<stopKey>shutdown</stopKey>
<stopPort>9966</stopPort>
</configuration>
</plugin>
</plugins>
</build>

写配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ssm_bookstore</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>bookstore</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring_MVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bookstore</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:application_Context.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

spring_MVC.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

<mvc:annotation-driven />
<context:component-scan base-package="com.bs.admin.controller"/>

<!-- 视图构造器   视图对象 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- 文件上传会用到 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2048000000"/>
<property name="maxInMemorySize" value="409600000"/>
<property name="maxUploadSizePerFile" value="2048000000"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>

<!-- 注册拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.bs.admin.interceptor.BookInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>

application_context.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

<context:component-scan base-package="com.bs.admin">
<context:exclude-filter type="regex" expression="$[A-Z]\w*Controller^"/>
</context:component-scan>
<!-- 导入spring myBatis整合的配置文件 -->
<import resource="classpath*:spring_mybatis.xml"/>
</beans>

spring_mybatis.xml

<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<!-- 选择并配置数据源,使用c3p0.ComboPooledDataSource会自动加载classpath下的c3p0.properties -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" />

<!-- 生成SessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 扫描实体类 -->
<property name="typeAliasesPackage" value="com.bs.admin.pojo" />
<!-- 扫描XxxMapper.xml, mapperLocations:指明Mapper.xml文件路径 -->
<property name="mapperLocations" value="classpath*:com/bs/admin/mapper/xml/*Mapper.xml" />
<!-- configuration:配置 -->
<property name="configuration">
<bean class="org.apache.ibatis.session.Configuration">
<!-- mapUnderscoreToCamelCase:将下划线映射到驼峰大小写 -->
<property name="mapUnderscoreToCamelCase" value="true" />
<!-- cacheEnabled:激活缓存 -->
<property name="cacheEnabled" value="true"/>
</bean>
</property>
</bean>

<!-- 注册接口文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConf
1aa70
igurer">
<property name="basePackage" value="com.bs.admin.mapper" />
</bean>

<!-- 事务控制 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 开启注解式事务 -->
<!-- <tx:annotation-driven/> -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- read-only="true" :  告诉mybatis只需要创建一个只读的Connection -->
<tx:method name="add*" propagation="REQUIRED" rollback-for="java.sql.SQLException" />
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.sql.SQLException" />
<tx:method name="modify*" propagation="REQUIRED" rollback-for="java.sql.SQLException" />
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>

<!-- 配置aop切口 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(public * com.bs.admin.service..*.*(..))" />
</aop:config>

</beans>

创建表

t_book

t_author

t_book_author 创建多对多的关系需要中间表

pojo实体类

书的实体类

package com.bs.admin.pojo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
*
* <p>Title: Book</p>
* <p>Description: Book实体类</p>
* @author Jack.Hu
* <p> @date 2018年11月21日</p>
*/
public class Book implements Serializable {

private static final long serialVersionUID = 597733879789573558L;
private Long primaryId;
private Long bookId;
private String bookName;
private Set<Author> authors = new HashSet<Author>(); // 作者与书,多对多
private String bookCategory;  // 书的种类
private Long bookPurchasePrice;  // 进价
private Long bookSalesPrice;  // 售价
private String bookProfile;  // 简介
private String bookCoverImage;  // 图片路径
private Long publisherId;  // 出版社id
private Long printId;  // 印刷id
private Set<Activity> activity = new HashSet<Activity>();  // 活动与书多对多

public Book(){

}
public Book(Long primaryId, Long bookId, String bookName, Set<Author> authors, String bookCategory, Long bookPurchasePrice,Long bookSalesPrice, String bookProfile, String bookCoverImage, Long publisherId, Long printId, Set<Activity> activity) {
this.primaryId = primaryId;
this.bookId = bookId;
this.bookName = bookName;
this.authors = authors;
this.bookCategory = bookCategory;
this.bookPurchasePrice = bookPurchasePrice;
this.bookSalesPrice = bookSalesPrice;
this.bookProfile = bookProfile;
this.bookCoverImage = bookCoverImage;
this.publisherId = publisherId;
this.printId = printId;
this.activity = activity;
}
@Override
public String toString() {
return "Book [主键:" + primaryId + ", 书号:" + bookId + ", 书名:" + bookName +", 作者:"+ authors + ", 种类:" + bookCategory + ", 进价:" + bookPurchasePrice + ", 售价:" + bookSalesPrice
+ ", 简介:" + bookProfile + ", 图片路径:" + bookCoverImage + ", 出版者id:" + publisherId + ", 印刷商id:" + printId +", 活动:" + activity + "]";
}
// .......忽略get set方法.......
}

作者的实体类

package com.bs.admin.pojo;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

/**
*
* <p>Title: Author</p>
* <p>Description: 作者的实体类</p>
* @author  jack.Hu
* <p> @date 2018年11月21日</p>
*/
public class Author implements Serializable {

private static final long serialVersionUID = -2631951426846305889L;
private Integer authorId;
private String authorName;
private Set<Book> books = new HashSet<Book>();

public Author(){

}
public Author(Integer authorId, String authorName, Set<Book> books) {
this.authorId = authorId;
this.authorName = authorName;
this.books = books;
}
@Override
public String toString() {
return "Author [authorId=" + authorId + ", authorName=" + authorName + ", book:" + books +"]";
}
// .......忽略get set方法.......
}

Mapper层

BookMapper.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.bs.admin.mapper.BookMapper">
<!-- 通过bookId查询书的信息 -->
<select id="getBookByBookId" resultMap="BookResultMap">
select <include refid="bookColumns"/>,<include refid="authorColumns"/>
from t_book b,t_author a,t_book_author ba
where ba.book_id = b.book_id
and ba.author_id = a.author_id
and b.book_id = #{bookId}
</select>

<resultMap type="book" id="BookResultMap" autoMapping="true">
<id property="primaryId" column="primary_id"/>
<!-- 多对多查询 -->
<collection property="authors" ofType="author" autoMapping="true"/>
</resultMap>

<sql id="bookColumns">
primary_id, b.book_id,b.book_name,b.book_category,b.book_purchasePrice,b.book_salesPrice,
b.book_profile,b.book_coverImage,b.publisher_id,b.print_id
</sql>

<sql id="authorColumns">
a.author_id, a.author_name
</sql>

</mapper>

BookMapper接口

package com.bs.admin.mapper;

import com.bs.admin.pojo.Book;

public interface BookMapper {

Book getBookByBookId(Long bookId);

Integer createBook(Book book);
}

dao层

接口

package com.bs.admin.dao;

import org.springframework.stereotype.Repository;

import com.bs.admin.pojo.Book;

@Repository
public interface BookDao {

Book retrieveBookByBookId(Long bookId);

}

实现类

package com.bs.admin.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.bs.admin.dao.BookDao;
import com.bs.admin.mapper.BookMapper;
import com.bs.admin.pojo.Book;

@Repository
public class BookDaoImpl implements BookDao {

@Autowired
private BookMapper bm;

@Override
public Book retrieveBookByBookId(Long bookId) {
Book book = bm.getBookByBookId(bookId);
return book;
}

}

service层

接口

package com.bs.admin.service;

import org.springframework.stereotype.Service;

import com.bs.admin.pojo.Book;

@Service
public interface  BookService {

Book getBookByBookId(Long bookId);
}

实现类

package com.bs.admin.service.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bs.admin.dao.BookDao;
import com.bs.admin.dao.impl.BookDaoImpl;
import com.bs.admin.pojo.Book;
import com.bs.admin.service.BookService;

@Service
public class BookServiceImpl implements BookService{

@Autowired
private BookDao bd;

@Override
public Book getBookByBookId(Long bookId) {
Book book = bd.retrieveBookByBookId(bookId);
return book;
}
}

controller层

BookstoreController

package com.bs.admin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.bs.admin.pojo.Author;
import com.bs.admin.pojo.Book;
import com.bs.admin.service.AuthorService;
import com.bs.admin.service.BookService;

@RestController
@RequestMapping("bookstore")
public class BookstoreController {

@Autowired
private BookService bs;

@Autowired
private AuthorService as;

@GetMapping("{bookId}/getBook")
public @ResponseBody Book getBook(@PathVariable("bookId") Long bookId) {
Book book = bs.getBookByBookId(bookId);
System.out.println("book对象:   " + book);
return book;
}
}

浏览器

控制台

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: