SSM高级整合-----CRUD

SSM-CRUD

1、环境搭建

​ 使用IDEA创建MavenWeb项目:并导入项目需要的依赖

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8tSfcLM4-1592193726130)(SSM高级整合-----CRUD.assets/image-20191227145718386.png)]

<dependencies>
    
    <dependency>
        <groupId>com.github.pagehelpergroupId>
        <artifactId>pagehelperartifactId>
        <version>5.0.0version>
    dependency>

    
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>4.3.7.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>4.3.7.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>4.3.7.RELEASEversion>
        <scope>compilescope>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aspectsartifactId>
        <version>4.3.7.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aopartifactId>
        <version>4.3.7.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.4.2version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>1.3.1version>
    dependency>

    
    <dependency>
        <groupId>c3p0groupId>
        <artifactId>c3p0artifactId>
        <version>0.9.1.2version>
    dependency>

    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.41version>
    dependency>

    
    <dependency>
        <groupId>jstlgroupId>
        <artifactId>jstlartifactId>
        <version>1.2version>
    dependency>

    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>javax.servlet-apiartifactId>
        <version>3.0.1version>
        <scope>providedscope>
    dependency>

    
    <dependency>
        <groupId>org.mybatis.generatorgroupId>
        <artifactId>mybatis-generator-coreartifactId>
        <version>1.3.5version>
    dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.8.8version>
    dependency>

    
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-validatorartifactId>
        <version>5.4.1.Finalversion>
    dependency>

    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>jsp-apiartifactId>
        <version>2.0version>
        <scope>providedscope>
    dependency>

    <dependency>
        <groupId>org.junit.jupitergroupId>
        <artifactId>junit-jupiter-apiartifactId>
        <version>RELEASEversion>
        <scope>compilescope>
    dependency>

    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
        <scope>compilescope>
    dependency>

    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.10version>
    dependency>
dependencies>

​ 数据库结构:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QLskaKwN-1592193726151)(SSM高级整合-----CRUD.assets/image-20191227152951262.png)]

2、配置web.xml


<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_4_0.xsd"
         id="WebApp_ID"
         version="4.0">

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>

    
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>springDispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:spring-mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springDispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
        <init-param>
            <param-name>forceRequestEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
        <init-param>
            <param-name>forceResponseEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <filter>
        <filter-name>corsfilter-name>
        <filter-class>com.zhangyong.filter.HeaderFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>corsfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <filter>
        <filter-name>HiddenHttpMethodFilterfilter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <filter>
        <filter-name>HttpPutFormContentFilterfilter-name>
        <filter-class>org.springframework.web.filter.HttpPutFormContentFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>HttpPutFormContentFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

web-app>

3、配置applicationContext.xml


<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.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.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.zhangyong">
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    context:component-scan>

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}">property>
        <property name="driverClass" value="${jdbc.driverClass}">property>
        <property name="user" value="${jdbc.user}">property>
        <property name="password" value="${jdbc.password}">property>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
        <property name="dataSource" ref="pooledDataSource">property>
        
        <property name="mapperLocations" value="classpath:mapper/*.xml" >property>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
        
        <property name="basePackage" value="com.zhangyong.dao">property>
    bean>

    
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="executorType" value="BATCH"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="pooledDataSource">property>
    bean>

    
    <aop:config>
        
        <aop:pointcut id="txPoint" expression="execution(* com.zhangyong.service..*(..))" >aop:pointcut>
        
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    aop:config>

    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            
            <tx:method name="*" />
            <tx:method name="get*" read-only="true"/>
        tx:attributes>
    tx:advice>

beans>

4、配置dbconfig.properties

jdbc.jdbcUrl=jdbc:mysql:///ssm_crud?useSSL=false&serverTimezone=UTC&user=root&password=&useUnicode=true&characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=521521

5、配置mybatis-config.xml(mybatis配置文件)



<configuration>
    
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>

    
    <typeAliases>
        <package name="com.zhangyong.bean">package>
    typeAliases>

    
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            
            <property name="reasonable" value="true"/>
        plugin>
    plugins>

configuration>

6、配置spring-mvc.xml


<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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    
    <context:component-scan base-package="com.zhangyong" use-default-filters="false">
        
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller">context:include-filter>
    context:component-scan>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/">property>
        <property name="suffix" value=".jsp">property>
    bean>

    
    
    <mvc:default-servlet-handler/>

    
    <mvc:annotation-driven/>
beans>

7、使用mybatis.generator生成实体类以及数据库接口和实现类

​ a、配置生成文件mbj.xml:




<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="521521">
        jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        javaTypeResolver>

        
        <javaModelGenerator targetPackage="com.zhangyong.bean"
                            targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true" />
        sqlMapGenerator>

        
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.zhangyong.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true" />
        javaClientGenerator>

        
        <table tableName="tbl_emp" domainObjectName="Employee">table>
        <table tableName="tbl_dept" domainObjectName="Department">table>
    context>
generatorConfiguration>

​ b、测试代码并生成MBGTest:

/**
 * 生成bean,mapper
 */
public class MBGTest {
    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<>();
        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);
    }
}
 	c、设置SpringMVC前后端分离的ajax的跨域:
public class HeaderFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) resp;
        //解决跨域访问报错
        response.setHeader ("Access-Control-Allow-Origin", "*");
        response.setHeader ("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        //设置过期时间
        response.setHeader ("Access-Control-Max-Age", "3600");
        response.setHeader ("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        // 支持HTTP 1.1.
        response.setHeader ("Cache-Control", "no-cache, no-store, must-revalidate");
        // 支持HTTP 1.0. response.setHeader("Expires", "0");
        response.setHeader ("Pragma", "no-cache");
        chain.doFilter (request, resp);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

​ d、整个代码结构和生成的代码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vP4Yn8WS-1592193726157)(SSM高级整合-----CRUD.assets/image-20200127124608332.png)]

8、生成的EmployeeMapper.xml不满足需求,我们希望查询员工的同时部门信息也是查询出来

更改实体类:Employee

/**
 * @author 张勇
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class Employee {
    private Integer empId;

    private String empName;

    private String gender;

    private String email;

    private Integer dId;

    /**
     * 希望查询员工的同时部门信息也是查询出来
     */
    private Department department;
}

添加employeeMapper

	/**
     * 带条件的查询,并且查出部门信息
     */
    List<Employee> selectByExampleWithDept(EmployeeExample example);

    /**
     * 根据Id查询,并且查出部门信息
     *
     * @param empId
     * @return
     */
    Employee selectByPrimaryKeyWithDept(Integer empId);

添加employeeMapper.xml

<resultMap id="WithDeptResultMap" type="com.zhangyong.bean.Employee">
    <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="com.zhangyong.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>
    <include refid="WithDept_Column_List" />
    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}*/ e.emp_id
    if>
  select>
  <select id="selectByPrimaryKeyWithDept" parameterType="java.lang.Integer" resultMap="WithDeptResultMap">
    select
    <include refid="WithDept_Column_List" />
    from tbl_emp e
    left join tbl_dept d on e.d_id = d.dept_id
    where emp_id = #{empId,jdbcType=INTEGER}
  select>

9、编写控制层EmployeeController,显示基本信息

/**
 * @Author 张勇
 * @Date 2019/12/27 22:20
 * @Version 1.0
 * 处理员工的CRUD请求
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 查询员工数据(分页查询)
     *
     * @return
     */
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model) {
        //添加分页查询:引入PageHelper分页插件
        //在查询之前只需要调用,传入页码,以及每页大小
        PageHelper.startPage (pn,5);
        //startPage后面紧跟的查询就是一个分页查询

        List<Employee> emps = employeeService.getAll ();

        //使用PageInfo来包装查询结果,只需要将PageInfo交给页面就行了
        //PageInfo封装了很多方法便于我们使用(如:总页数,上一页,下一页……)
        //5表示连续显示的页数
        PageInfo page = new PageInfo (emps,5);

        //使用model将值带入前端
        model.addAttribute ("pageInfo",page);

        return "list";
    }
}

10、编写EmployeeService层:

/**
 * @Author 张勇
 * @Date 2019/12/27 22:25
 * @Version 1.0
 */
@Service
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 查询所有员工
     * @return
     */
    public List<Employee> getAll() {
        return employeeMapper.selectByExampleWithDept (null);
    }
}

11、EmployeeControllerTest测试代码:

/**
 * @Author 张勇
 * @Date 2019/12/27 22:52
 * @Version 1.0
 * 使用Spring测试模块提供的测试请求功能,测试crud请求的准确性
 * spring4测试的时候,需要3.0以上的Servlet Api以上
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:spring-mvc.xml"})
public class EmployeeControllerTest {

    //传入SpringMVC的ioc
    @Autowired
    WebApplicationContext context;
    //虚拟MVC请求,获取到处理结果
    MockMvc mockMvc;

    @Before
    public void initMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup (context).build ();
    }

    @Test
    public void getEmps() throws Exception {
        //模拟请求拿到的返回值
        MvcResult result = mockMvc.perform (MockMvcRequestBuilders.get ("/emps").param ("pn", "1"))
                .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 num : nums) {
            System.out.print (" " + num);
        }

        //获取员工数据
        List<Employee> list = pi.getList ();
        for (Employee employee : list) {
            System.out.println ("ID:" + employee.getEmpId () + "====>Name:" + employee.getEmpName ());
        }
    }
}

kHttpServletRequest 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 num : nums) {
System.out.print (" " + num);
}

    //获取员工数据
    List list = pi.getList ();
    for (Employee employee : list) {
        System.out.println ("ID:" + employee.getEmpId () + "====>Name:" + employee.getEmpName ());
    }
}

}


你可能感兴趣的:(spring,mybatis)