SSM框架搭建過程

  1. 引入依賴的jar包(pom.xml)
a. <!--Spring SpringMVC相關-->  spring-webmvc
b. <!--Spring事務-->  spring-jdbc
c. <!--面向切面編程-->  spring-aspects
d. <!--mybatis-->  mybatis
e. <!--mybatis 整合 spring-->  mybatis-spring
f. <!--數據庫鏈接池、驅動-->  c3p0  mysql-connector-java
g. <!--jstl,servlet-api-->  jstl  javax.servlet-api
h. <!— MBG-->  mybatis-generator-core
i. <!— junit-->  junit
  1. webapp/WEB-INF/web.xml 中
  2. src/main/resources目錄下新建applicationContext.xml
  3. web.xml同級目錄下新建dispatcherServlet-servlet.xml並配置
    1. 掃描控制器
    2. 配置視圖解析器
    3. <!--兩個標準配置  -->
a. 服務器一啓動就啓動Spring 容器
b. springMVC前端控制器
c. 字符編碼過濾器,必定要放在全部過濾器以前
d. 使用Rest風格的URI,將頁面普通的post請求轉爲指定的
delete或者put請求

        <!-- 將springmvc不能處理的請求交給tomcat -->前端

       <!-- 能支持springmvc更高級的一些功能-->java

  1. 配置Spring在applicationContext.xml中

a. 掃描除控制器之外的其餘組件mysql

b. 配置數據源(同時將dbconfig.properties文件導入到resources目錄下)git

c. 配置和MyBatis的整合,同時在src/main/resources下建立mybaitis的配置文件mybatis-config.xml以及mapper文件夾github

d. 配置掃描器,將mybatis接口的實現加入到ioc容器中web

e. 配置一個能夠執行批量的sqlSessionspring

f. 配置事務控制sql

g. xml配置事務<!-- 切入點表達式 *表示返回值類型 ,表示com.cn.crud.service包下的,..表示即便有子包仍然能夠,表達式表達的是該包下的全部方法都能切入事務-->數據庫

h. 配置事務加強,事務如何切入編程

  1. 配置MyBatis在mybatis-config.xml中
  2. 在當前工程下建立mbg.xml進行配置,使用mybatis 逆向工程生成對應的bean 、dao和 mapper
  3. mbg.xml文件
  4. <?xml version="1.0" encoding="UTF-8"?>
    <!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="com.atguigu.crud.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="com.atguigu.crud.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>

  5. Mybatis逆向工程測試

public class MBGTest {

     public static void main(String[] args) throws Exception {

          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);

     }

}

  1. 修改mapper文件

其中,<resultMap id="BaseResultMap_Dept" type="com.cn.crud.bean.Employee">
  <result column="emp_id" jdbcType="INTEGER" property="empId" />
  <result column="emp_name" jdbcType="VARCHAR" property="empName" />
  <result column="emp_gender" jdbcType="CHAR" property="empGender" />
  <result column="emp_email" jdbcType="VARCHAR" property="empEmail" />
  <result column="d_id" jdbcType="INTEGER" property="dId" />
  <association

property="department" javaType="com.cn.crud.bean.Department">
    <id column="dept_id" property="deptId"/>
    <result column="dept_name" property="deptName"/>
</association>

</resultMap>

<association> 關聯查詢,瞭解

 10.  * 測試dao層的工做

 *推薦Spring的項目就可使用Spring的單元測試,能夠自動注入咱們須要的組件

 *一、導入SpringTest模塊

      在pom.xml中引入spring-test依賴

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->

<dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-test</artifactId>

    <version>5.1.3.RELEASE</version>

    <scope>test</scope>

</dependency>

 *二、@ContextConfiguration指定Spring配置文件的位置

 *三、直接autowired要使用的組件便可

 */

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:applicationContext.xml"})

public class MapperTest {

    

     @Autowired

     DepartmentMapper departmentMapper;

 

     @Autowired

     EmployeeMapper employeeMapper;

    

     @Autowired

     SqlSession sqlSession;

    

     /**

      * 測試DepartmentMapper

      */

     @Test

     public void testCRUD(){

     /*   //一、建立SpringIOC容器

          ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");

          //二、從容器中獲取mapper

          DepartmentMapper bean = ioc.getBean(DepartmentMapper.class);*/

          System.out.println(departmentMapper);

         

          //一、插入幾個部門

//        departmentMapper.insertSelective(new Department(null, "開發部"));

//        departmentMapper.insertSelective(new Department(null, "測試部"));

         

          //二、生成員工數據,測試員工插入

          employeeMapper.insertSelective(new Employee(null, "Jerry", "M", "Jerry@atguigu.com", 1));

         

          //三、批量插入多個員工;批量,使用能夠執行批量操做的sqlSession。

         

//        for(){

//              employeeMapper.insertSelective(new Employee(null, , "M", "Jerry@atguigu.com", 1));

//        }

          EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);

          for(int i = 0;i<1000;i++){

                String uid = UUID.randomUUID().toString().substring(0,5)+i;

                mapper.insertSelective(new Employee(null,uid, "M", uid+"@atguigu.com", 1));

          }

          System.out.println("批量完成");

         

     }

 

}

11.  分頁使用插件pagehelper

須要在pom.xml中引入依賴

<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.1.8</version>
</dependency>

其餘配置查看:

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

  1. 12.  Spring分頁測試代碼

@RunWith(SpringJUnit4ClassRunner.class)

@WebAppConfiguration

@ContextConfiguration(locations = { "classpath:applicationContext.xml",

          "file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml" })

public class MvcTest {

     // 傳入Springmvc的ioc

     @Autowired

     WebApplicationContext context;

     // 虛擬mvc請求,獲取處處理結果。

     MockMvc mockMvc;

 

     @Before

     public void initMokcMvc() {

          mockMvc = MockMvcBuilders.webAppContextSetup(context).build();

     }

 

     @Test

     public void testPage() throws Exception {

          //模擬請求拿到返回值

          MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "5"))

                     .andReturn();

         

          //請求成功之後,請求域中會有pageInfo;咱們能夠取出pageInfo進行驗證

          MockHttpServletRequest request = result.getRequest();

          PageInfo pi = (PageInfo) request.getAttribute("pageInfo");

          System.out.println("當前頁碼:"+pi.getPageNum());

          System.out.println("總頁碼:"+pi.getPages());

          System.out.println("總記錄數:"+pi.getTotal());

          System.out.println("在頁面須要連續顯示的頁碼");

          int[] nums = pi.getNavigatepageNums();

          for (int i : nums) {

                System.out.print(" "+i);

          }

         

          //獲取員工數據

          List<Employee> list = pi.getList();

          for (Employee employee : list) {

                System.out.println("ID:"+employee.getEmpId()+"==>Name:"+employee.getEmpName());

          }

         

     }

 

}

13. @ResponseBody
 @ResponseBody 能夠把返回的對象轉換爲json串,要想其正常工做須要導入jackson包:jackson-databind
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>
</dependency>
 

14.  rest風格的URI

 

相關文章
相關標籤/搜索