• SpringBoot------整合MyBatis


    1.添加pom.xml需要的依赖

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>top.ytheng</groupId>
      <artifactId>springboot-demo</artifactId>
      <version>0.0.1</version>
      <packaging>jar</packaging>
      
      <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.5.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <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>
            
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            
            <!-- 热部署 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <optional>true</optional>
                  <scope>true</scope>
            </dependency>
            
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.2</version>
                <scope>runtime</scope>
            </dependency>
            
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.6</version>
            </dependency>
        </dependencies>
    
        <build>
            <!-- 打包的名称 -->
            <finalName>myspringboot</finalName>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    2.添加Entity

    package top.ytheng.demo.entity;
    
    import org.springframework.stereotype.Component;
    import java.lang.String;
    import java.util.Date;
    
    public class UserInfo {
        private int id;
        private String username;
        private String password;
        private Date createTime;
        
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public Date getCreateTime() {
            return createTime;
        }
        public void setCreateTime(Date createTime) {
            this.createTime = createTime;
        }
        public UserInfo() {
            super();
        }
        public UserInfo(String username, String password) {
            super();
            this.username = username;
            this.password = password;
        }
    }

    3.添加UserMapper.java

    package top.ytheng.demo.mapper;
    
    import java.util.List;
    
    import org.apache.ibatis.annotations.Delete;
    import org.apache.ibatis.annotations.Insert;
    import org.apache.ibatis.annotations.Options;
    import org.apache.ibatis.annotations.Result;
    import org.apache.ibatis.annotations.Results;
    import org.apache.ibatis.annotations.Select;
    import org.apache.ibatis.annotations.Update;
    
    import top.ytheng.demo.entity.UserInfo;
    
    public interface UserMapper {
    
        //#{}里面的名称要和UserInfo里面的一一对应
        //推荐使用#{},不要使用${},会存在注入风险
        @Insert("Insert INTO user_info(username,password) VALUES(#{username},#{password})")
        //保存对象,获取数据库自增id
        //keyProperty对应UserInfo对象中的id
        //keyColumn对应数据库user_info表中的id
        @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
        int insert(UserInfo user);
        
        //查找全部
        @Select("SELECT * FROM user_info")
        @Results({
            @Result(column="create_time", property="createTime"),
            //@Result(column="update_time", property="updateTime"),
        })
        List<UserInfo> getAll();
        
        //根据id找对象
        @Select("SELECT * FROM user_info WHERE id = #{id}")
        @Results({
            @Result(column="create_time", property="createTime"),
        })
        UserInfo findById(int id);
        
        //更新对象
        @Update("UPDATE user_info SET username= #{username} WHERE id = #{id}")
        void update(UserInfo user);
        
        //删除对象
        @Delete("DELETE FROM user_info WHERE id = #{userid}")
        void delete(int userid);
    }

    4.添加UserService.java

    package top.ytheng.demo.service;
    
    import java.util.List;
    
    import top.ytheng.demo.entity.UserInfo;
    
    public interface UserService {
    
        public int add(UserInfo user);
        
        public List<UserInfo> getAll();
        
        public UserInfo findById(int id);
        
        public void update(UserInfo user);
        
        public void delete(int id);
    }

    5.添加UserServiceImpl.java

    package top.ytheng.demo.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import top.ytheng.demo.entity.UserInfo;
    import top.ytheng.demo.mapper.UserMapper;
    import top.ytheng.demo.service.UserService;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
        
        @Override
        public int add(UserInfo user) {
            // TODO Auto-generated method stub
            userMapper.insert(user);
            int id = user.getId();
            return id;
        }
    
        @Override
        public List<UserInfo> getAll() {
            // TODO Auto-generated method stub
            List<UserInfo> users = userMapper.getAll();
            return users;
        }
    
        @Override
        public UserInfo findById(int id) {
            // TODO Auto-generated method stub
            UserInfo user = userMapper.findById(id);
            return user;
        }
    
        @Override
        public void update(UserInfo user) {
            // TODO Auto-generated method stub
            userMapper.update(user);
        }
    
        @Override
        public void delete(int id) {
            // TODO Auto-generated method stub
            userMapper.delete(id);
        }
    }

    6.添加Controller

    package top.ytheng.demo.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import top.ytheng.demo.entity.UserInfo;
    import top.ytheng.demo.service.UserService;
    
    @RestController
    @RequestMapping("/api/v1/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
        
        @GetMapping("/add")
        public Object add() {
            UserInfo user = new UserInfo();
            user.setUsername("theng");
            user.setPassword("123456");
            int id = userService.add(user);
            return id;
        }
        
        @GetMapping("/getall")
        public Object getAll() {
            List<UserInfo> users = userService.getAll();
            return users;
        }
        
        @GetMapping("/findbyid")
        public Object findById(@RequestParam(name="id")int id) {
            UserInfo user = userService.findById(id);
            return user;
        }
        
        @GetMapping("/update")
        public Object update() {
            UserInfo user = userService.findById(2);
            user.setUsername("朱竹清");
            userService.update(user);
            return "update success";
        }
        
        @GetMapping("/delete")
        public Object delete(@RequestParam(name="id")int id) {
            userService.delete(id);
            return "delete success";
        }
    }

    7.添加配置文件application.properties

    #端口号
    server.port=8080
    
    #数据库的一些配置
    #mybatis.type-aliases-package=top.ytheng.demo
    #会自动识别
    #spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    #数据库连接
    spring.datasource.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8&useSSL=false
    spring.datasource.username=root
    spring.datasource.password=123456
    #使用阿里巴巴数据源,默认的数据源(com.zaxxer.hikari.KikariDataSource)
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    #开启控制台打印sql
    mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

    8.添加启动类

    package top.ytheng.demo;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    
    @SpringBootApplication //等于下面3个
    //@SpringBootConfiguration
    //@EnableAutoConfiguration
    //@ComponentScan
    //拦截器用到
    @ServletComponentScan
    //MyBatis用到
    @MapperScan("top.ytheng.demo.mapper")
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    }

    9.安装MySQL数据库,添加数据库shop,表user_info

    10.右键项目Run As启动,访问url

    http://localhost:8080/api/v1/user/getall
    http://localhost:8080/api/v1/user/add
    http://localhost:8080/api/v1/user/findbyid?id=1
    http://localhost:8080/api/v1/user/update
    http://localhost:8080/api/v1/user/delete?id=10

    另附:

  • 相关阅读:
    博客中引用的概念
    重构博客写作
    做中学之教与学工具箱
    做中学之效率工具箱
    两个月选一本理想教材
    《敏捷革命》读书笔记
    《Java2 实用教程(第五版)》学习指导
    得到.每天听本书
    「2017年教育部-永信至诚产学合作协同育人网络空间安全专业课程教学研讨会」参会总结
    Ditto在教学上的应用
  • 原文地址:https://www.cnblogs.com/tianhengblogs/p/9807604.html
Copyright © 2020-2023  润新知