zoukankan      html  css  js  c++  java
  • SpringBoot整合mybatis

    首先导入mybatis依赖

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.0.0</version>
            </dependency>

    创建mapper包,并在Application启动类中添加包扫描@MapperScan 扫描mapper文件

    @SpringBootApplication
    @MapperScan("com.cyitce.springcache.mapper")  //mapper 文件的包路径
    public class SpringCacheApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringCacheApplication.class, args);
        }
    
    }

    application.properties中配置数据源

    spring.datasource.url=jdbc:mysql://localhost:3306/database
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.username=username
    spring.datasource.password=password

    以下是简单实现

    User.java

    public class User implements Serializable{
    
        private Long id;
    
        private String username;
    
        private String password;
    
        private String email;
    
        private String role;
        
        
        //省略get/set方法
    }

    UserMapper.java  注意添加@Mapper注解

    @Mapper
    public interface UserMapper {
    
        @Select("select * from user where id = #{id}")
        public User getUserById(Long id);
    }

    将UserMapper 注入到Service或者Controller中直接使用  如果出现mapper无法注入,idea报错信息请忽略(spring 容器没有找到,不影响程序启动)

    UserServiceImpl.java

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        UserMapper userMapper;
    
    
        @Override
        public User getUserById(Long id) {
            User userById = userMapper.getUserById(id);
            return userById;
        }
    }

    UserController.java

    @RestController
    public class UserController {
        @Autowired
        UserService userService;
    
        @RequestMapping("/getUser/{id}")
        public User getUser(@PathVariable("id") String id){
            User userById = userService.getUserById(Long.parseLong(id));
            return userById;
        }
    }

    简单的springboot 整合mabatis就实现了。。。。

  • 相关阅读:
    云原生时代,微服务到底应该怎么玩儿?
    坐上机器猫的时光机,来一场科技穿越之旅吧
    喜讯|京东荣获2019 【中国技术品牌影响力企业】
    非洲正在打造一个与硅谷完全不同的人工智能产业
    DevOps专题|基础Agent部署系统
    《编写可读代码的艺术》总结
    《Effective Java第二版》总结
    MySQL之备份和还原
    MySQL之Xtrabackup的使用
    MySQL之mysqldump的使用
  • 原文地址:https://www.cnblogs.com/linux0kk/p/12175737.html
Copyright © 2011-2022 走看看