SSM整合之CRUD環境搭建整合

cherry...a發表於2020-11-26

SSM整合之CRUD環境搭建整合

基礎框架-ssm(SpringMVC+Spring+MyBatis)
資料庫-MySQL
前端框架-bootstrap快速搭建簡潔美觀的介面
專案的依賴管理-Maven
分頁-pagehelper
逆向工程-MyBatis Generator
  1. 在pom.xml中引入相應的jar包
 <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!--鎖定jar包的版本-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>
    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>

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

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

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

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

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</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>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <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>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 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

2.補全maven工程的目錄結構,並建立對應的包
org.westos.controller
org.westos.service
org.westos.dao
org.westos.bean
org.westos.utils
org.westos.test

3.引入bootstrap

https://www.bootcss.com/ 進入官網

下載完成後解壓壓縮包,在webapp下鍵一個static資料夾,放靜態資源,也就是將解壓後的bootstrap資料夾放進去

在index.jsp頁面引入bootstrap

<%--引入bootstrap的樣式--%>
   <link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <%--引入引入bootstrap的js檔案--%>
    <script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

bootstrap 要用到Jquery 所以還得引入一下Jquery的檔案,注意放在最前面引入

我們可以在static下再建一個js資料夾把Jquery的庫檔案放到這個資料夾下
	<%--引入Jquery--%>
	<script src="static/js/jquery-1.12.4.min.js"></script>

4.編寫SSM整合的配置檔案

  1. 配置web.xml檔案(算是固定模板了,SSM中都是這些配置)

    <?xml version="1.0" encoding="UTF-8" ?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://java.sun.com/xml/ns/javaee"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
             id="WebApp_ID" version="2.5">
      <!--配置一個監聽器,去載入spring的配置檔案
       ContextLoaderListener 預設載入的是WEB-INF下的spring的配置檔案
       -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <!--配置監聽器,去載入類路徑下的applicationContext.xml配置檔案,不然預設載入的是WEB-INF下的配置檔案-->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
        <!--配置SpringMVC的前端控制器-->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--去載入springmvc.xml配置檔案-->
        <!--配置載入springmvc.xml 配置檔案-->
      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
      </init-param>
        <!--配置伺服器啟動,就初始化DispatcherServlet-->
        <load-on-startup>1</load-on-startup>
      </servlet>
    <servlet-mapping>
      <servlet-name>dispatcherServlet</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>
      <!--配置post請求的中文亂碼的過濾器,注意這個過濾器要放在其他過濾器之前-->
      <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!--配置restful風格請求的過濾器:作用將頁面上的普通的post請求轉換為
        put或delete請求
      -->
      <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    </web-app>
    
    
  2. 編寫Springmvc的配置檔案

    1.在resources下建立 springmvc.xml
    2.配置註解掃描,只掃描@Controller註解
    3.配置檢視解析器
    4.將springmvc不能處理的靜態資源,交由tomcat來處理
    5.開啟對SpringMVC註解的支援

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
            
            
           <!--開啟註解掃描 只掃描@Controller-->
        <context:component-scan base-package="org.westos">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
    
        <!--配置檢視解析器-->
    
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
            <!-- JSP檔案所在的目錄 -->
            <property name="prefix" value="/WEB-INF/views/"></property>
            <!-- 檔案的字尾名 -->
            <property name="suffix" value=".jsp"></property>
        </bean>
    
    
        <!--將springmvc不能處理的靜態資源,交由tomcat來處理,因為我們這邊使用bootstrap-->
        <mvc:default-servlet-handler></mvc:default-servlet-handler>
    
        <!-- 開啟對SpringMVC註解的支援 -->
        <mvc:annotation-driven/>
     </beans> 
    
  3. 配置Springmvc的配置檔案applicationContext…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:aop="http://www.springframework.org/schema/aop"
           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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd    http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        <!--開啟元件的註解掃描 除去springmvc不要掃描-->
        <context:component-scan base-package="org.westos">
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
        
        <!--配置資料來源-->
        <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"/>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm_crud"/>
            <property name="user" value="root"/>
            <property name="password" value="123456"/>
        </bean>
        
        <!--配置和MyBatis的整合-->
        <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
            <!--指定mybatis的全域性配置檔案-->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
            <!--指定MyBatis 介面的對映檔案的位置 掃描-->
            <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
            <!--注入連線池-->
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--配置掃描器,將mybatis的介面實現放到IOC容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="org.westos.dao"></property>
        </bean>
        
        <!--配置事務相關-->
        <!--配置事務管理器,傳入連線池-->
        <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!--開啟基於註解的事務,使用xml配置形式的事務(一般主要的都是使用配置式)  -->
        <aop:config>
            <!-- 切入點表示式  org.westos.service..*(..) 注意 ..* 的意思是service包下的所有類,包括子包下的所有類-->
            <aop:pointcut expression="execution(public * org.westos.service..*(..))" id="txPoint"/>
            <!-- 配置事務增強 -->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
        </aop:config>
    
        <!--配置事務增強,事務如何切入  -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <!-- 所有方法都是事務方法 -->
                <tx:method name="*"/>
                <!--以get開始的查詢所有方法 read-only="true" 可以不使用事務 -->
                <tx:method name="get*" read-only="true"/>
            </tx:attributes>
        </tx:advice>
    
    </beans>    
        
    
  4. 配置MyBatis的全域性配置檔案**

     <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <settings>
            <!--開啟駝峰式命名-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        </settings>
        <typeAliases>
            <!--給bean包下的實體類配置別名-->
            <package name="org.westos.bean"/>
        </typeAliases>
    </configuration>
    
  5. 建立表

    1.員工表
    CREATE TABLE `tbl_emp` (
      `emp_id` int(11) NOT NULL AUTO_INCREMENT,
      `emp_name` varchar(255) NOT NULL,
      `gender` char(1) DEFAULT NULL,
      `email` varchar(255) DEFAULT NULL,
      `d_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`emp_id`) -- 員工的部門編號 外來鍵可以關聯 部門表的主鍵
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    
    2.部門表
    CREATE TABLE `tbl_dept` (
      `dept_id` int(11) NOT NULL AUTO_INCREMENT,
      `dept_name` varchar(255) NOT NULL,
      PRIMARY KEY (`dept_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    
    
    3. 可以新增兩張表的外來鍵約束 員工表是多表 部門表是單表
    ALTER TABLE `tbl_emp` ADD FOREIGN KEY(`d_id`) REFERENCES tbl_dept(dept_id);
    
  6. 使用逆向工程根據資料庫中的表來生成對應的bean以及mapper

    要使用逆向工程先在pom.xml中引入相應的jar包
      		<dependency>
    			<groupId>org.mybatis.generator</groupId>
    			<artifactId>mybatis-generator-core</artifactId>
    			<version>1.3.5</version>
    		</dependency>
    在當前工程根目錄下建立一個mbg.xml檔案 用來配置要生成的bean 和 mapper的資訊
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    <generatorConfiguration>
    
        <context id="DB2Tables" targetRuntime="MyBatis3">
            <!--配置生成出來的程式碼中不要新增註釋,如果要註釋就不要配置,預設會有註釋-->
            <commentGenerator>
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <!-- 配置資料庫連線 -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/ssm_crud" userId="root"
                            password="123456">
            </jdbcConnection>
    
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
    
            <!-- 指定javaBean生成的位置 -->
            <javaModelGenerator targetPackage="org.westos.bean"
                                targetProject=".\src\main\java">
                <property name="enableSubPackages" value="true"/>
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!--指定sql對映檔案生成的位置 -->
            <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
                <property name="enableSubPackages" value="true"/>
            </sqlMapGenerator>
    
            <!-- 指定dao介面生成的位置,mapper介面 -->
            <javaClientGenerator type="XMLMAPPER"
                                 targetPackage="org.westos.dao" targetProject=".\src\main\java">
                <property name="enableSubPackages" value="true"/>
            </javaClientGenerator>
    
    
            <!-- table指定每個表的生成策略 配置表名和對應的實體類名 -->
            <table tableName="tbl_emp" domainObjectName="Employee"></table>
            <table tableName="tbl_dept" domainObjectName="Department"></table>
        </context>
    </generatorConfiguration>
    使用逆向工程的程式碼和逆向工程的配置檔案來生成對應的bean和mapper
     在org.westos.test 包下建一個類執行下面的程式碼
       
      
      public class MyTest {
        public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            //載入當前工程下的逆向工程的配置檔案
            File configFile = new File("mbg.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(configFile);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
                    callback, warnings);
            myBatisGenerator.generate(null);
        }
    }
    
    
  7. 給 EmployeeMapper.xml 對映檔案中 增加查詢時帶上部門資訊的設定

對員工的查詢時,只是單表查詢,並沒有帶上員工的部門資訊。
所以我們在增加兩個查詢,在查詢員工時帶上部門資訊。也就是說需要多表查詢

員工表和部門表是一對一的關係。

需要在員工的實體類中維護一個部門實體類的物件,來體現一對一的關係。

 private Integer empId;

        private String empName;

        private String gender;

        private String email;

        private Integer dId;

        //維護一個部門實體類的物件
        private Department department;
        /get set 方法略 自己補上

在生成的 EmployeeMapper 介面中增加兩個查詢的方法,查詢員工時帶上部門資訊

public interface EmployeeMapper {
   		 //根據條件查詢多個員工幷包含部門資訊
       List<Employee> selectByExampleWithDept(EmployeeExample example);
   		 //根據id查詢單個員工幷包含部門資訊
       Employee selectByPrimaryKeyWithDept(Integer empId);
    // ... 其他自動生成的方法略

   }

在EmployeeMapper.xml 對映檔案中配置一對一的關係

 <resultMap type="org.westos.bean.Employee" id="WithDeptResultMap">
    <id column="emp_id" jdbcType="INTEGER" property="empId"/>
    <result column="emp_name" jdbcType="VARCHAR" property="empName"/>
    <result column="gender" jdbcType="CHAR" property="gender"/>
    <result column="email" jdbcType="VARCHAR" property="email"/>
    <result column="d_id" jdbcType="INTEGER" property="dId"/>
    <!--配置一對一的關係 指定聯合查詢出的部門欄位的封裝 -->
    <association property="department" javaType="org.westos.bean.Department">
      <id column="dept_id" property="deptId"/>
      <result column="dept_name" property="deptName"/>
    </association>
  </resultMap>

新增查詢標籤

!-- 查詢員工同時帶部門資訊 -->
  <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
	   select
	    <if test="distinct">
	      distinct
	    </if>
	   e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name
		FROM tbl_emp e
		left join tbl_dept d on e.`d_id`=d.`dept_id`
	    <if test="_parameter != null">
	      <include refid="Example_Where_Clause" />
	    </if>
	    <if test="orderByClause != null">
	      order by ${orderByClause}
	    </if>
  </select>
   <!--根據id查詢單個員工時,帶上部門資訊-->
    <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
        select e.emp_id,
               e.emp_name,
               e.gender,
               e.email,
               e.d_id,
               d.dept_id,
               d.dept_name
        FROM tbl_emp e
                 left join tbl_dept d on e.`d_id` = d.`dept_id`
        where emp_id = #{empId,jdbcType=INTEGER}
    </select>
5.測試Dao增刪改查的操作
如果是Maven專案則在pom.xml中引入spring-test.jar的座標
		注意jar的依賴範圍scope不要設定為test
	   <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

編寫測試類


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class MapperTest {
//注入
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private SqlSession sqlSession;
    @Test
    public void test(){
        //1.先來插入幾個部門
        Department dept1 = new Department();
        dept1.setDeptName("後勤部");
        departmentMapper.insertSelective(dept1);

        Department dept2 = new Department();
        dept2.setDeptName("藝術部");
        departmentMapper.insertSelective(dept2);
    }
    @Test
    public void test2(){
        //插入一個員工
        Employee employee = new Employee();
        employee.setEmpName("劉德華");
        employee.setGender("M");
        employee.setEmail("liudehua@163.com");
        employee.setdId(1);
        employeeMapper.insertSelective(employee);
    }
    @Test
    public void test3(){
        Employee employee = employeeMapper.selectByPrimaryKeyWithDept(1);
        System.out.println(employee);
    }
    @Test
    public void test4(){
        List<Employee> employees = employeeMapper.selectByExampleWithDept(null);
        System.out.println(employees);
    }
   
}

為了我們多插入點員工,可以使用批量插入
我們需要在Spring的配置檔案applicationContext.xml中配置一個SqlSessionTemplate 可以進行批量操作的sqlSession

    <!--配置一個可以執行批量操作的sqlSeesion-->
<bean class="org.mybatis.spring.SqlSessionTemplate" id="sessionTemplate">
    <constructor-arg name="sqlSessionFactory" ref="sessionFactory"></constructor-arg>
    <!--執行型別,是BATCH 批量執行-->
    <constructor-arg name="executorType" value="BATCH"></constructor-arg>
</bean>
	注入sqlSession
   	 @Autowired
    private SqlSession sqlSession;
@Test
    public void test5(){
        //批量插入員工
        //通過sqlSession 獲取一個可以執行批量操作的mapper
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        for (int i = 0; i < 100; i++) {
            Employee employee = new Employee(null, "zhangxueyou" + i, "M", "zhangxueyou@163.com", 1, null);
            mapper.insertSelective(employee);
        }
    }

相關文章