• MyBatis多对多增删改查(不建关联实体)


    MyBatis多对多增删改查(不建关联实体)

    标签: mvcmybatis增删改查
     分类:
     

    目录(?)[+]

     

    写在前面

    本文的出发点在于:本人师傅比较NB,在项目中数据库操作用的MyBatis,需要涉及到多对多的操作,问师傅多对多是否需要建立关联实体,师傅说了句“低级的可以建,高级的不需要”,于是乎,为了挑战难度,在项目中最终以不建立关联实体解决了多对多的操作问题。于是空闲的时间自己用spring-mvc 4MyBatis 、MySQL 、Maven从零搭建起一个 简单的demo,一是为了从头到尾巩固理解,二是为了留着以后忘记了可以查阅,三是也希望能帮助到一些像我这样菜鸟级别的人。此片文章可能非常长,我写的步骤也算很细了,NB的人肯定认为很累赘,不过重在分享!

    环境工具

    • 操作系统:Windows 7
    • 开发工具:Intellij IDEA 14
    • 数据库连接:Navicat 11 Premium
    • 接口测试:Postman

    demo要完成的功能

    • 对学生student的操作:学生学号必须唯一 
      • 添加学生信息;
      • 修改学生信息;
      • 按学号查询学生信息;
      • 查询所有学生信息(不加载所选教师信息);
      • 查询所有学生信息(同时加载所选教师信息);
    • 对教师teacher的操作:教师工号必须唯一 
      • 添加教师信息;
      • 修改教师信息;
      • 按工号查询教师信息;
      • 查询所有教师信息(不加载所教学生信息);
      • 查询所有教师信息(同时加载所教学生信息);
    • 对关联表student_teacher的操作:学生选授课教师 
      • 学生选择多个授课教师,关联信息插入关联表中

    demo依赖jar包说明

    • junit-3.8.1.jar:用于单元测试;
    • spring-jdbc-4.1.6.RELEASE.jar:事务管理;
    • spring-webmvc-4.1.6.RELEASE.jar:spring-mvc 4必须;
    • spring-aspects-4.1.6.RELEASE.jar:面向切面编程;
    • mybatis-3.2.8.jar:MyBatis必须;
    • mybatis-spring-1.2.2.jar:MyBatis整合spring所需;
    • commons-dbcp-1.4.jar:数据库连接池;
    • slf4j-log4j12-1.7.7.jar:打印日志;
    • servlet-api-2.5.jar:servlet容器所需
    • fastjson-1.1.36.jar:json数据转换工具;
    • jackson-databind-2.3.3.jar:序列化类为json格式数据所需;
    • mysql-connector-java-5.1.32.jar:java连接MySQL数据库驱动包

    开发步骤

    第一步:新建数据库

    1.ER图: 
    学生教师ER图

    2.student表: 
    学生表

    3.teacher表: 
    教师表

    4.关联表student_teacher: 
    关联表

    5.关联表增加外键与student和teacher关联: 
    外键关联


    第二步:新建Maven工程

    1.新建maven webapp工程: 
    新建工程

    2.填写maven坐标: 
    maven坐标

    3.新建完成的工程: 
    工程结构

    4.配置maven: 
    (1).maven home directory:maven解压后所在的路径; 
    (2).usere settings file:maven conf目录下的setting文件,具体配置略; 
    (3).local repository:本地maven仓库所在的目录,用于存放jar 
    maven配置


    第三步:搭建项目结构

    新建entity包、dao包、service包、impl包、controller包,结构按需自定义 
    项目结构


    第四步:配置开发环境参数

    修改项目编码:三处均为 “UTF-8” 
    修改编码


    第五步:增加所有jar依赖到pom.xml

    添加项目所需的所有jar的maven坐标:

    <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>4.1.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>4.1.6.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>4.1.6.RELEASE</version>
            </dependency>
            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.2.8</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.2.2</version>
            </dependency>
            <dependency>
                <groupId>commons-dbcp</groupId>
                <artifactId>commons-dbcp</artifactId>
                <version>1.4</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.7</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.1.36</version>
            </dependency>
    
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.3.3</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.32</version>
                <scope>runtime</scope>
            </dependency>
        </dependencies>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67

    第六步:配置application.development.properties和applicationContext.xml

    1. application.development.properties:数据库连接参数以及数据库连接池参数;
    #mysql database setting
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1/mybatis-demo?useUnicode=true&characterEncoding=utf-8
    jdbc.username=user
    jdbc.password=123456
    
    #connection pool settings
    jdbc.pool.minIdle=3
    jdbc.pool.maxIdle=5
    jdbc.pool.maxActive=15
    jdbc.pool.maxWait=120000
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2 . applicationContext.xml:spring容器核心配置

    <?xml version="1.0" encoding="UTF-8"?>
    <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:p="http://www.springframework.org/schema/p"
           xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
    
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
           default-lazy-init="true">
        <description>Spring公共配置</description>
        <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->
        <context:annotation-config/>
        <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
        <context:component-scan base-package="com.xiaolong.demo"/>
    
        <!-- MyBatis配置 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
            <property name="typeAliasesPackage" value="com.xiaolong.demo"/>
            <!-- 显式指定Mapper文件位置 -->
            <property name="mapperLocations" value="classpath:/mybatis/*Mapper.xml"/>
        </bean>
        <!-- 扫描basePackage下所有以@MyBatisRepository标识的 接口 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.xiaolong.demo.dao"/>
            <property name="annotationClass"
                      value="com.xiaolong.demo.dao.MyBatisRepository"/>
        </bean>
    
        <!-- 使用annotation定义事务 -->
        <tx:annotation-driven proxy-target-class="true"/>
        <bean id="transactionManager" name="transactionManager"
              class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource">
                <ref bean="dataSource"/>
            </property>
        </bean>
        <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
            <!--<tx:attributes>-->
                <!--<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>-->
            <!--</tx:attributes>-->
        </tx:advice>
        <aop:config proxy-target-class="true">
            <aop:pointcut id="transactionPointcut"
                          expression="execution(* com.xiaolong.demo.service.impl.*.*(..))"/>
            <aop:advisor pointcut-ref="transactionPointcut"
                         advice-ref="transactionAdvice"/>
        </aop:config>
    
        <!-- local development环境 -->
        <beans profile="development">
            <context:property-placeholder
                    ignore-resource-not-found="true"
                    location="classpath*:/application.development.properties"/>
    
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
                <property name="driverClassName" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
    
                <property name="maxActive">
                    <value>${jdbc.pool.maxActive}</value>
                </property>
                <property name="maxIdle">
                    <value>${jdbc.pool.maxIdle}</value>
                </property>
                <property name="minIdle">
                    <value>${jdbc.pool.minIdle}</value>
                </property>
                <property name="maxWait">
                    <value>${jdbc.pool.maxWait}</value>
                </property>
            </bean>
            <bean id="studentService" class="com.xiaolong.demo.service.impl.StudentServiceImpl" />
            <bean id="teacherService" class="com.xiaolong.demo.service.impl.TeacherServiceImpl" />
        </beans>
    </beans>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    第七步:配置spring-mvc.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <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"
           xmlns="http://www.springframework.org/schema/beans"
           xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
        <!-- 自动扫描且只扫描@Controller -->
        <context:component-scan base-package="com.xiaolong.demo" use-default-filters="false">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:include-filter type="annotation"
                                    expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
        </context:component-scan>
    
        <!--<context:property-placeholder location="/WEB-INF/*.properties"/>-->
    
        <mvc:annotation-driven>
            <mvc:message-converters register-defaults="true">
                <!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    </beans>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    第七步:新建实体Student和Teacher

    Student实体:

    public class Student {
        private Integer id;                 //id
        private String name;                //姓名
        private String number;              //学号,保证唯一
        private String gender;              //性别
        private Integer age;                //年龄
        private List<Teacher> teachers;     //授课老师集合
        ..........省略get、set............
      }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Teacher实体:

    public class Teacher {
        private Integer id;                 //id
        private String name;                //姓名
        private String number;              //工号,保证唯一
        private String gender;              //性别
        private Integer age;                //年龄
        private List<Student> students;     //所教学生集合
        ............省略get、set方法.....................   
     }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    第八步:新建StudentMyBatisDao接口

    在此之前需要先写个注解类MyBatisRepository

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.TYPE})
    public @interface MyBatisRepository {
    }
    • 1
    • 2
    • 3
    • 4

    然后新建StudentMyBatisDao接口

    @MyBatisRepository
    public interface StudentMyBatisDao {
        int addStudent(Student student);
    
        int updateStudent(Student student);
    
        Student findStudentByNumber(String number);
    
        Student findStudentById(Long id);
    
        List<Student> findAll();
    
        List<Student> findAllWithTeachers();
    
        int selectTeachers(Long studentId, List<Long> teacherIds);
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    第九步:编写MyBatis的StudentMapper.xml

    说明:这里我使用了查询结果的继承关系,当不需要查询列表是resultMap就写studentMap,当需要将教师信息同时加载时返回的resultMap就是studentTeacherMap。另外,多对多在插入关联表的时候我使用的是批量插入,用了foreach,param2代表第二个集合参数

    <?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">
    <!-- namespace必须指向Dao接口 -->
    <mapper namespace="com.xiaolong.demo.dao.StudentMyBatisDao">
        <!--查询结果不包含app列表-->
        <resultMap id="studentMap" type="com.xiaolong.demo.entity.Student">
            <id column="id" property="id" jdbcType="BIGINT"/>
    
            <result column="name" property="name" jdbcType="VARCHAR"/>
            <result column="number" property="number" jdbcType="VARCHAR"/>
            <result column="gender" property="gender" jdbcType="VARCHAR"/>
            <result column="age" property="age" jdbcType="INTEGER"/>
        </resultMap>
        <!--查询的时候将教师列表一起查询出来-->
        <resultMap id="studentTeacherMap" type="com.xiaolong.demo.entity.Student"
                   extends="studentMap">
            <collection property="teachers" ofType="com.xiaolong.demo.entity.Teacher">
                <id property="id" column="t_id" jdbcType="BIGINT"/>
    
                <result property="name" column="t_name" jdbcType="VARCHAR"/>
                <result property="number" column="t_number" jdbcType="VARCHAR"/>
                <result property="gender" column="t_gender" jdbcType="VARCHAR"/>
                <result property="age" column="t_age" jdbcType="INTEGER"/>
            </collection>
        </resultMap>
    
    
        <sql id="columns">
            id,name,number,gender,age
        </sql>
    
        <select id="findStudentByNumber" resultMap="studentMap" parameterType="java.lang.String">
            SELECT
            <include refid="columns"/>
            FROM student
            WHERE number=#{0}
        </select>
    
        <select id="findStudentById" resultMap="studentTeacherMap" parameterType="java.lang.Long">
            SELECT
            s.id,s.name,s.number,s.gender,s.age,
    
            t.id as t_id,t.name as t_name,t.number as t_number,t.gender as t_gender,t.age as t_age
            FROM
            student s LEFT JOIN student_teacher st
            ON s.id=st.s_id
            LEFT JOIN teacher t
            ON t.id=st.t_id
            WHERE s.id=#{0}
        </select>
    
        <select id="findAll" resultMap="studentMap">
            SELECT * FROM student
        </select>
    
        <select id="findAllWithTeachers" resultMap="studentTeacherMap">
            SELECT
            s.id,s.name,s.number,s.gender,s.age,
    
            t.id as t_id,t.name as t_name,t.number as t_number,t.gender as t_gender,t.age as t_age
            FROM
            student s LEFT JOIN student_teacher st
            ON s.id=st.s_id
            LEFT JOIN teacher t
            ON t.id=st.t_id
        </select>
    
        <insert id="addStudent" parameterType="com.xiaolong.demo.entity.Student">
            insert into student
            (
            name,number,gender,age
            )
            values
            (
            #{name,jdbcType=VARCHAR},#{number,jdbcType=VARCHAR},#{gender,jdbcType=VARCHAR},#{age,jdbcType=INTEGER}
            )
        </insert>
        <update id="updateStudent" parameterType="com.xiaolong.demo.entity.Student">
            update student
            <set>
                <if test="name != null">
                    name = #{name,jdbcType=VARCHAR},
                </if>
                <if test="number != null">
                    number = #{number,jdbcType=VARCHAR},
                </if>
                <if test="gender != null">
                    gender = #{gender,jdbcType=VARCHAR},
                </if>
                <if test="age != null">
                    age = #{age,jdbcType=INTEGER},
                </if>
            </set>
            where id=#{id,jdbcType=BIGINT}
        </update>
        <!--/*这种方式使用批量插入*/-->
        <insert id="selectTeachers">
    
            INSERT INTO student_teacher
            (s_id,t_id)
            VALUES
            <foreach collection="param2" item="id" separator=",">
                (#{0}, #{id})
            </foreach>
    
        </insert>
    </mapper> 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108

    第十步:编写StudentService接口

    功能包括:对学生的增删改查以及学生选择教师

    public interface StudentService {
        public void addStudent(Student student) throws Exception;
    
        public void updateStudent(Student student) throws Exception;
    
        public Student findStudentByNumber(String number);
    
        public List<Student> findAll();
    
        public List<Student> findAllWithTeachers();
    
        public void selectTeachers(Long studentId,List<Long> teacherIds)throws Exception;
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    第十一步:编写StudentServiceImpl实现类

    在添加和修改是我手动判断了学号是否重复

    package com.xiaolong.demo.service.impl;
    
    import com.alibaba.fastjson.JSONObject;
    import com.xiaolong.demo.dao.StudentMyBatisDao;
    import com.xiaolong.demo.entity.Student;
    import com.xiaolong.demo.entity.Teacher;
    import com.xiaolong.demo.service.StudentService;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    
    /**
     * Created by xiaolong.zhu on 2015/6/4.
     */
    @SuppressWarnings("ALL")
    @Transactional
    @Component
    public class StudentServiceImpl implements StudentService {
        private static final Logger logger = LoggerFactory.getLogger(StudentServiceImpl.class);
        @Autowired
        private StudentMyBatisDao studentMyBatisDao;
    
        @Override
        public void addStudent(Student student) throws Exception {
            logger.info("添加学生信息{}", JSONObject.toJSONString(student));
            Student another = studentMyBatisDao.findStudentByNumber(student.getNumber());
            if (another != null && another.getId() != student.getId())
                throw new Exception("参数异常,number重复");
            int result = studentMyBatisDao.addStudent(student);
            if (result != 1)
                throw new Exception("添加学生信息失败");
        }
    
        @Override
        public void updateStudent(Student student) throws Exception {
            logger.info("修改学生信息{}", JSONObject.toJSONString(student));
            if (student.getId() == null)
                throw new Exception("参数异常,id为null");
            Student another = studentMyBatisDao.findStudentByNumber(student.getNumber());
            if (another != null && another.getId() != student.getId())
                throw new Exception("参数异常,number重复");
            int result = studentMyBatisDao.updateStudent(student);
            if (result != 1)
                throw new Exception("修改学生信息失败");
        }
    
        @Override
        public Student findStudentByNumber(String number) {
            logger.info("通过学号{}查询学生信息", number);
            Student student = studentMyBatisDao.findStudentByNumber(number);
            return student;
        }
    
        @Override
        public List<Student> findAll() {
            logger.info("查询所有学生信息");
            return studentMyBatisDao.findAll();
        }
    
        @Override
        public List<Student> findAllWithTeachers() {
            logger.info("查询所有学生信息及授课老师");
            return studentMyBatisDao.findAllWithTeachers();
        }
    
        @Override
        public void selectTeachers(Long studentId, List<Long> teacherIds) throws Exception {
            logger.info("学生{}选择授课老师{}", studentId, teacherIds.toArray());
            Student student = studentMyBatisDao.findStudentById(studentId);
            for (Teacher teacher : student.getTeachers()) {
                if (teacher != null) {
                    if (teacherIds.contains(teacher.getId()))
                        throw new Exception("参数异常,该学生" + studentId + "已经选择了此教师" + teacher.getId() + ",不允许重复操作");
                }
            }
            int result = studentMyBatisDao.selectTeachers(studentId, teacherIds);
            if (result != teacherIds.size())
                throw new Exception("参数异常,教师id错误");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85

    在完成StudentServiceImpl之后,为了在Controller中能用@Autowired自动注入,需要将StudentServiceImpl在spring容器中注册,见applicationContext.xml


    第十二步:编写StudentController类

    说明:由于用的spring mvc 4,所以@ResponseBody就不用在写了,它已经写在了注解类@RestController中了。另外,ip是获取客户端真是ip,若使用了代理,就从header中取得,未使用代理,就使用request.getRemoteHost()得到。

    package com.xiaolong.demo.controller;
    
    import com.alibaba.fastjson.JSONObject;
    import com.xiaolong.demo.entity.Student;
    import com.xiaolong.demo.service.StudentService;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.List;
    
    
    /**
     * Created by xiaolong.zhu on 2015/6/4.
     */
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @RestController
    @RequestMapping(value = "/demo/", consumes = {MediaType.ALL_VALUE})
    public class StudentController {
        private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
    
        @Autowired
        private StudentService studentService;
    
        @RequestMapping(value = "student", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity addStudent(@RequestBody Student student, HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null)
                ip = request.getRemoteHost();
            logger.info("ip {} 正添加新的学生信息{}", ip, JSONObject.toJSONString(student));
            try {
                studentService.addStudent(student);
                return new ResponseEntity(null, HttpStatus.OK);
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
                JSONObject error = new JSONObject();
                error.put("error", e.getMessage());
                return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
            }
        }
    
        @RequestMapping(value = "student", method = RequestMethod.PUT, consumes = {MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity updateStudent(@RequestBody Student student, HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null)
                ip = request.getRemoteHost();
            logger.info("ip {} 正修改学生信息{}", ip, JSONObject.toJSONString(student));
            try {
                studentService.updateStudent(student);
                return new ResponseEntity(null, HttpStatus.OK);
            } catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
                JSONObject error = new JSONObject();
                error.put("error", e.getMessage());
                return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
            }
        }
    
        @RequestMapping(value = "student/{number}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity findByNumber(@PathVariable("number") String number,
                                           HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null)
                ip = request.getRemoteHost();
            logger.info("ip {} 正通过学号{}获取学生信息", ip, number);
            Student student = studentService.findStudentByNumber(number);
            return new ResponseEntity(student, HttpStatus.OK);
        }
    
    
        @RequestMapping(value = "students", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity findAll(HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null)
                ip = request.getRemoteHost();
            logger.info("ip {} 获取所有学生信息", ip);
            List<Student> students = studentService.findAll();
            return new ResponseEntity(students, HttpStatus.OK);
        }
    
        @RequestMapping(value = "students/teachers", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity findAllWithTeachers(HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null)
                ip = request.getRemoteHost();
            logger.info("ip {} 获取所有学生信息以及其授课老师", ip);
            List<Student> students = studentService.findAllWithTeachers();
            return new ResponseEntity(students, HttpStatus.OK);
        }
    
        @RequestMapping(value = "student/{id}/teachers", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity selectTeachers(@PathVariable("id") Long studentId,
                                             @RequestBody JSONObject ids,
                                             HttpServletRequest request) {
            String ip = request.getHeader("X-Forwarded-For");
            if (ip == null)
                ip = request.getRemoteHost();
            logger.info("ip {} 学生{}选择授课老师{}",ip,studentId,ids.toJSONString());
            try {
                studentService.selectTeachers(studentId, (List<Long>) ids.get("teacherIds"));
                return new ResponseEntity(null, HttpStatus.OK);
            }catch (Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
                JSONObject error = new JSONObject();
                error.put("error", e.getMessage());
                return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
            }
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117

    第十三步:测试Student操作的接口

    所有接口集合: 
    所有接口

    1.测试添加学生信息: 
    添加学生

    2.测试修改学生信息: 
    修改学生

    3.测试按学号查询学生信息: 
    按学号查询学生

    4.测试查询学生信息集合(不包含授课教师): 
    查询学生集合

    5.测试查询学生信息集合(包含授课教师): 
    查询学生集合

    6.测试学生选择教师(批量): 
    若学生重复选择某一个教师,则不允许 
    重复选择

    成功选择教师 
    选择教师

    操作结果: 
    操作结果

    第十四步:新建TeacherMyBatisDao接口

    同学生部分

    第十五步:编写MyBatis的TeacherMapper.xml

    同学生部分

    第十六步:编写TeacherService接口

    同学生部分

    第十七步:编写TeacherServiceImpl实现类

    同学生部分

    第十八步:编写TeacherController类

    同学生部分

    第十九步:测试Teacher操作的接口

    同学生部分

    线上接口

    demo部署在我服务器使用如下ip地址及端口号即可调用上述所有接口

    敬请期待….

  • 相关阅读:
    centos6升级内核
    centos7启动盘制作
    sed匹配字符串并将匹配行的后几行注释
    cmd下调用xshell登录linux服务器
    centos清除历史命令
    yum错误Cannot retrieve metalink for repository: epel/x86_6
    ansible-playbook
    jdk升级到1.8
    shell瞎记录
    shell 循环
  • 原文地址:https://www.cnblogs.com/liuyingke/p/7741733.html
Copyright © 2020-2023  润新知