SSM整合框架之多對多查詢

什麼是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>
	
</beans>

<font color=red>**application_context.xml**</font>

    <?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.MapperScannerConfigurer">
		<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;
    	}
    }

瀏覽器
在這裏插入圖片描述

控制檯
在這裏插入圖片描述

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