mybatis-ssm整合

环境

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80022
 Source Host           : localhost:3306
 Source Schema         : school

 Target Server Type    : MySQL
 Target Server Version : 80022
 File Encoding         : 65001

 Date: 20/11/2021 17:20:00
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `tea_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `tea_age` int(0) NULL DEFAULT NULL,
  `tea_email` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 65 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES (1, 'set', 22, 'tom@qq.com');
INSERT INTO `teacher` VALUES (2, 'lili', 22, 'lili@qq.com');
INSERT INTO `teacher` VALUES (3, 'lucy', 22, 'lucy@qq.com');
INSERT INTO `teacher` VALUES (4, 'lisi', 22, 'lisi@qq.com');
INSERT INTO `teacher` VALUES (62, 'teacher1', 22, '1@qq.com');
INSERT INTO `teacher` VALUES (63, 'teacher2', 22, '2@qq.com');
INSERT INTO `teacher` VALUES (64, 'teacher3', 22, '3@qq.com');

SET FOREIGN_KEY_CHECKS = 1;

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
db.username=root
db.password=123456
#dbconfig.properties
# Global logging configuration
log4j.rootLogger=debug, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
#log4j.properties
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!--mybatis-config.xml-->
	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true"/>
	</settings>
	
	<databaseIdProvider type="DB_VENDOR">
		<property name="MySQL" value="mysql"/>
		<property name="Oracle" value="oracle"/>
		<property name="SQL Server" value="sqlserver"/>
	</databaseIdProvider>
	
</configuration>
<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--applicationContext.xml-->
    <!--引入配置文件-->
    <context:property-placeholder location="classpath:dbconfig.properties" />
    <!--数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

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

    <!--扫描com.fly.mapper下的接口,自动创建代理类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.fly.mapper"/>
    </bean>

    <!--事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <tx:advice id="txAdvice">
        <tx:attributes>
            <tx:method name="get*" propagation="SUPPORTS"/>
            <tx:method name="add*"/>
            <tx:method name="update*"/>
            <tx:method name="del*"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>

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

    <context:component-scan base-package="com"/>

</beans>

<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--springmvc-servlet.xml-->
    <context:component-scan base-package="com.fly.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 字符串格式的消息转换器,用于设置响应结果的字符集编码,处理ajax乱码问题 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <!-- fastjson自带的对象json转换的消息转换器,用于将对象转为json格式的字符串返回给客户端 -->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
                <!-- 设置日期格式转换的格式为yyyy-MM-dd -->
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <import resource="applicationContext.xml"/>

    <!--配置文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>


</beans>

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--web.xml-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- SpringMVC配置 -->
    <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
package com.fly.entity;

import java.io.Serializable;

/**
 * @author 26414
 */
public class Teacher implements Serializable {

  private Integer id;
  private String teaName;
  private Integer teaAge;
  private String teaEmail;

  @Override
  public String toString() {
    return "Teacher{" +
            "id=" + id +
            ", teaName='" + teaName + '\'' +
            ", teaAge=" + teaAge +
            ", teaEmail='" + teaEmail + '\'' +
            '}';
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getTeaName() {
    return teaName;
  }

  public void setTeaName(String teaName) {
    this.teaName = teaName;
  }

  public Integer getTeaAge() {
    return teaAge;
  }

  public void setTeaAge(Integer teaAge) {
    this.teaAge = teaAge;
  }

  public String getTeaEmail() {
    return teaEmail;
  }

  public void setTeaEmail(String teaEmail) {
    this.teaEmail = teaEmail;
  }
}

package com.fly.mapper;

import com.fly.entity.Teacher;
import org.apache.ibatis.annotations.Mapper;

/**
 * @author 26414
 */
@Mapper
public interface TeacherMapper {

  /**
   * 根据id查询老师
   * @param id id
   * @return 老师
   */
  Teacher getTeacherById(Integer id);

}

<?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">
<mapper namespace="com.fly.mapper.TeacherMapper">

    <select id="getTeacherById" resultType="com.fly.entity.Teacher">
        select * from teacher where id = #{id}
    </select>
</mapper>
package com.fly.service;

import com.fly.entity.Teacher;

/**
 * @author 26414
 */
public interface TeacherService {

  /**
   * 根据id查询老师
   * @param id id
   * @return 老师
   */
  Teacher getTeacherById(Integer id);

}

package com.fly.service.impl;

import com.fly.entity.Teacher;
import com.fly.mapper.TeacherMapper;
import com.fly.service.TeacherService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 26414
 */
@Service
public class TeacherMapperImpl implements TeacherService {

  @Resource
  private TeacherMapper teacherMapper;

  @Override
  public Teacher getTeacherById(Integer id) {
    return teacherMapper.getTeacherById(id);
  }
}

package com.fly.controller;

import com.alibaba.fastjson.JSON;
import com.fly.entity.Teacher;
import com.fly.service.TeacherService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 26414
 */
@RestController
public class TeacherController {

  @Resource
  private TeacherService teacherService;

  @RequestMapping("/get/{id}")
  public String getTeacherById(@PathVariable Integer id) {
    Teacher teacher = teacherService.getTeacherById(id);
    return JSON.toJSONString(teacher);
  }

}

测试

posted @ 2021-11-20 17:30  翻蹄亮掌一皮鞋  阅读(116)  评论(0)    收藏  举报