本文的出发点在于:本人师傅比较NB,在项目中数据库操作用的MyBatis,需要涉及到多对多的操作,问师傅多对多是否需要建立关联实体,师傅说了句“低级的可以建,高级的不需要”,于是乎,为了挑战难度,在项目中最终以不建立关联实体解决了多对多的操作问题。于是空闲的时间自己用
spring-mvc 4
、MyBatis
、MySQL
、Maven
从零搭建起一个 简单的demo,一是为了从头到尾巩固理解,二是为了留着以后忘记了可以查阅,三是也希望能帮助到一些像我这样菜鸟级别的人。此片文章可能非常长,我写的步骤也算很细了,NB的人肯定认为很累赘,不过重在分享!
- 操作系统:Windows 7
- 开发工具:Intellij IDEA 14
- 数据库连接:Navicat 11 Premium
- 接口测试:Postman
- 对学生student的操作:学生学号必须唯一
- 添加学生信息;
- 修改学生信息;
- 按学号查询学生信息;
- 查询所有学生信息(不加载所选教师信息);
- 查询所有学生信息(同时加载所选教师信息);
- 对教师teacher的操作:教师工号必须唯一
- 添加教师信息;
- 修改教师信息;
- 按工号查询教师信息;
- 查询所有教师信息(不加载所教学生信息);
- 查询所有教师信息(同时加载所教学生信息);
- 对关联表student_teacher的操作:学生选授课教师
- 学生选择多个授课教师,关联信息插入关联表中
- 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数据库驱动包
4.配置maven:
(1).maven home directory:maven解压后所在的路径;
(2).usere settings file:maven conf目录下的setting文件,具体配置略;
(3).local repository:本地maven仓库所在的目录,用于存放jar
添加项目所需的所有jar的maven坐标:
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.1.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.1.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>4.1.6.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.8version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.2version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.7version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.1.36version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.3.3version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.32version>
<scope>runtimescope>
dependency>
dependencies>
#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
2 . applicationContext.xml:spring容器核心配置
<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>
<context:annotation-config/>
<context:component-scan base-package="com.xiaolong.demo"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.xiaolong.demo"/>
<property name="mapperLocations" value="classpath:/mybatis/*Mapper.xml"/>
bean>
<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>
<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: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>
<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>
<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">
<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>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
mvc:message-converters>
mvc:annotation-driven>
beans>
Student实体:
public class Student {
private Integer id; //id
private String name; //姓名
private String number; //学号,保证唯一
private String gender; //性别
private Integer age; //年龄
private List teachers; //授课老师集合
..........省略get、set............
}
Teacher实体:
public class Teacher {
private Integer id; //id
private String name; //姓名
private String number; //工号,保证唯一
private String gender; //性别
private Integer age; //年龄
private List students; //所教学生集合
............省略get、set方法.....................
}
在此之前需要先写个注解类MyBatisRepository
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface MyBatisRepository {
}
然后新建StudentMyBatisDao接口
@MyBatisRepository
public interface StudentMyBatisDao {
int addStudent(Student student);
int updateStudent(Student student);
Student findStudentByNumber(String number);
Student findStudentById(Long id);
List findAll();
List findAllWithTeachers();
int selectTeachers(Long studentId, List teacherIds);
}
说明:这里我使用了查询结果的继承关系,当不需要查询列表是resultMap就写studentMap,当需要将教师信息同时加载时返回的resultMap就是studentTeacherMap。另外,多对多在插入关联表的时候我使用的是批量插入,用了foreach,param2代表第二个集合参数
<mapper namespace="com.xiaolong.demo.dao.StudentMyBatisDao">
<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>
功能包括:对学生的增删改查以及学生选择教师
public interface StudentService {
public void addStudent(Student student) throws Exception;
public void updateStudent(Student student) throws Exception;
public Student findStudentByNumber(String number);
public List findAll();
public List findAllWithTeachers();
public void selectTeachers(Long studentId,List teacherIds)throws Exception;
}
在添加和修改是我手动判断了学号是否重复
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 findAll() {
logger.info("查询所有学生信息");
return studentMyBatisDao.findAll();
}
@Override
public List findAllWithTeachers() {
logger.info("查询所有学生信息及授课老师");
return studentMyBatisDao.findAllWithTeachers();
}
@Override
public void selectTeachers(Long studentId, List 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错误");
}
}
在完成StudentServiceImpl之后,为了在Controller中能用@Autowired
自动注入,需要将StudentServiceImpl在spring容器中注册,见applicationContext.xml
说明:由于用的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 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 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) 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);
}
}
}
同学生部分
同学生部分
同学生部分
同学生部分
同学生部分
同学生部分
demo部署在我服务器使用如下ip地址及端口号即可调用上述所有接口
敬请期待….
- Q Q:1250052380
- 邮箱:[email protected]