zoukankan      html  css  js  c++  java
  • springboot集成mysql及mybatis

    springboo机集成mybatis及mysql

    1,添加依赖

    <?xml version="1.0"?>
    <project
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
        xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <modelVersion>4.0.0</modelVersion>
    
    
        <!-- 项目信息 begin -->
        <groupId>com.microservice</groupId>
        <artifactId>spring-web</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring-web</name>
        <url>http://maven.apache.org</url>
        <!-- 项目信息end -->
        <!-- 属性配置 begin -->
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
        <!-- 属性配置end -->
        <!-- 父依赖 begin -->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.4.1.RELEASE</version>
            <relativePath /> <!-- lookup parent from repository -->
        </parent>
        <!-- 父依赖 end -->
        <dependencies>
            <!-- 添加web包 begin -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <!-- 该包中包含requestMapping restController 等注解 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <!-- 添加web包 end -->
            <!-- mybatis依赖 begin -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version>
            </dependency>
            <!-- mybatis依赖 end -->
            <!-- mysql数据库配置 begin -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <!-- mysql数据库配置 end -->    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            
        </dependencies>
    </project>

    添加该配置时,需要注意mybatis和spring版本冲突问题。如果发生冲突,会导致一些奇怪的问题,例如注解(@Mapper)不成功。要解决该问题,可以参考网址https://start.spring.io/,配置版本。

    2,添加配置信息

    #系统中用到的参数配置  编码格式
    com.interview.question=springboot有哪些配置的注解
    #数据库连接配置信息
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    #spring.datasource.url = jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
    spring.datasource.url = jdbc:mysql://localhost:3306/shop
    spring.datasource.username = root
    spring.datasource.password = root
    #mybatis数据库映射文件配置
    mybatis.config-locations=classpath:mybatis/mybatis-config.xml
    mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

    mybatis-config.xml————数据类型的别名

    <configuration>
        <typeAliases>
            <typeAlias alias="Integer" type="java.lang.Integer" />
            <typeAlias alias="Long" type="java.lang.Long" />
            <typeAlias alias="HashMap" type="java.util.HashMap" />
            <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
            <typeAlias alias="ArrayList" type="java.util.ArrayList" />
            <typeAlias alias="LinkedList" type="java.util.LinkedList" />
        </typeAliases>
    </configuration>

    *.xml——配置mybatis数据库映射文件

    例如UserMapper.xml

    <?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="org.spring.web.mapper.UserMapper" >

    <resultMap id="BaseResultMap" type="org.spring.web.entity.User" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="passWord" property="passWord" jdbcType="VARCHAR" />
    <result column="user_name" property="userName" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="Base_Column_List" >
    id, user_name,age, passWord
    </sql>

    <!-- 查询用户 -->
    <select id="selectUserById" resultMap="BaseResultMap" parameterType="Integer">
    select
    <include refid="Base_Column_List" />
    from user where id=#{id}
    </select>
    <update id="updateUser" parameterType="org.spring.web.entity.User" >
    UPDATE
    user
    SET
    <if test="age != null and age!=''">age = #{age},</if>
    <if test="passWord != null and passWord!=''">passWord = #{passWord},</if>
    user_name = #{userName}
    WHERE
    id = #{id}
    </update>

    </mapper>

    3,XXMapper.xml对应的XXMapper.java类,该类和XXMapper.xml是对应的,为接口,其中的方法名和XXMapper.xml中sql的id是一致的。

    package org.spring.web.mapper;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.spring.web.entity.User;
    import org.springframework.stereotype.Component;
    
    /**
    *
    * 项目名称:spring-web
    * 类名称:UserMapper
    * 类描述:
    * 创建人:john
    * 创建时间:2018年7月28日 上午11:57:18
    * 修改人:john
    * 修改时间:2018年7月28日 上午11:57:18
    * 修改备注:
    * @version
    *
    */
    @Mapper
    //@Component
    
    public interface UserMapper {
        /*
         * 用户新增
         */
       public int inserUser(User user);
       
       public User selectUserById(Integer id);
       
       public int updateUser(User user);
    }

    @Mapper 注入该类,也可以在启动类直接添加 @MapperScan("org.spring.web.mapper") ,其中的参数是XXMapper.java所在的位置。@MapperScan("")和在XXMapper.java上添加@Mapper的作用是一样的。

    4,编写数据库服务接口层

    package org.spring.web.service;
    
    import org.spring.web.entity.User;
    import org.springframework.stereotype.Service;
    
    /**
    *
    * 项目名称:spring-web
    * 类名称:UserService
    * 类描述:
    * 创建人:john
    * 创建时间:2018年7月28日 上午11:52:50
    * 修改人:john
    * 修改时间:2018年7月28日 上午11:52:50
    * 修改备注:
    * @version
    *
    */
    
    
    public interface UserService {
       public int inserUser(User user);
       
       public User selectUserById(Integer id);
       
       public int updateUser(User user);
       
       public String getUser();
    
    }

    数据服务接口实现层

    package org.spring.web.service.serviceImpl;
    
    import java.util.concurrent.TimeUnit;
    
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.spring.web.entity.User;
    import org.spring.web.mapper.UserMapper;
    import org.spring.web.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.stereotype.Service;
    
    /**
    *
    * 项目名称:spring-web
    * 类名称:UserServiceImpl
    * 类描述:
    * 创建人:john
    * 创建时间:2018年7月28日 上午11:53:16
    * 修改人:john
    * 修改时间:2018年7月28日 上午11:53:16
    * 修改备注:
    * @version
    *
    */
    @Service
    public class UserServiceImpl  implements  UserService{
      private static Logger logger =LoggerFactory.getLogger(UserServiceImpl.class);
    
    
        @Autowired
        private UserMapper userMapper;
        @Autowired
        private RedisTemplate redisTemplate;
        
        public int inserUser(User user) {
            return 0;
        }
    
        public User selectUserById(Integer id) {
            User user=userMapper.selectUserById(id);
            System.out.println("根据用户ID>>"+id+"查询的用户信息>>>>>."+user);
            return user;
        }
    
        
        @Override
        public int updateUser(User user) {
            return userMapper.updateUser(user);
        }
    
        
        @Override
        public String getUser() {
             User user=new User();
             user.setId(22);
             user.setUserName("interview");
             ValueOperations<String, User> operations=redisTemplate.opsForValue();
             operations.set("com.yfli", user);
             operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
             try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }        
                //redisTemplate.delete("com.neo.f");
                boolean exists=redisTemplate.hasKey("com.neo.f");
                if(exists){
                    System.out.println("exists is true");
                }else{
                    System.out.println("exists is false");
                }     
                User redisUser=operations.get("com.yfli");
               return redisUser.toString();
        }
    
    }

    数据接口实现层添加@Service注解就可以了,接口层不用添加注解。如果实现层不添加注解,main方法启动的时候报错。

    5,controller层

    package org.spring.web.controller;
    
    import org.spring.web.entity.User;
    import org.spring.web.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
    *
    * 项目名称:spring-web
    * 类名称:UserController
    * 类描述:
    * 创建人:john
    * 创建时间:2018年7月28日 下午12:15:36
    * 修改人:john
    * 修改时间:2018年7月28日 下午12:15:36
    * 修改备注:
    * @version
    *
    */
    @RestController
    @RequestMapping("/user")
    public class UserController {
        @Autowired
        UserService userService;
        @RequestMapping("/selectByUserId")
        public User selectByUserId(Integer id){
            id=1;
            return userService.selectUserById(id);
        }
        
        @RequestMapping("/updateUser")
        public int updateUser(User user){
            user.setPassword("222");
            user.setUserName("你好");
            user.setAge(110);
            user.setId(1);
            
            return userService.updateUser(user);
        }
        
        @RequestMapping("/getRedisUser")
        public String getRedisUser(){
            return userService.getUser();
        }
    }

    controller层注入接口层,直接调用服务层的逻辑即可,程序的处理逻辑放在服务实现层。controller只需要接受参数,处理简单的转化逻辑即可。

    重点:设计restfule接口风格(待完善)

  • 相关阅读:
    [Java] SSH框架笔记_框架分析+环境搭建+实例源码下载
    [JavaEE] WEB-INF有关的目录路径总结
    网站标题分隔符
    [Windows] 解决kmplayer播放rmvb文件音视不同步
    [MySQL] 数据统计 —— 按周,按月,按日分组统计数据
    [Java] JSTL格式化时间计算时差
    [C.Sharp] TimeSpan的用法,获取测试程序运行时间
    [设计模式] .NET设计模式笔记
    Spring Boot使用redis做数据缓存
    Spring Boot使用redis做数据缓存
  • 原文地址:https://www.cnblogs.com/li-zhan/p/9391613.html
Copyright © 2011-2022 走看看