美文网首页springboot
SpingBoot整合Mybatis示例

SpingBoot整合Mybatis示例

作者: Coding测试 | 来源:发表于2020-03-12 18:13 被阅读0次

以下示例非常适合新人练手
本章项目源码下载地址:https://github.com/rootczy/spingboot-mybatis

  • 创建maven工程


  • pom文件引入mybatis

<!--引入spingboot框架-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • 添加数据库配置文件
# application.properties配置jpa模板
server.port=8090
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/interface-test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC 
spring.datasource.username=root
spring.datasource.password=000000
  • 创建数据库表信息
CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `userName` varchar(32) NOT NULL,
  `passWord` varchar(50) NOT NULL,
  `realName` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

添加两条测试数据如下:


  • 分别在项目包(com.interfacetest)下创建entry、mapper、service、controller包
    完整项目目录如下图:


  • 创建启动类

@SpringBootApplication
@EnableScheduling
public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
  • 实体类编写
@Data //使用lombok
public class User {
    private Integer id;
    private String userName;
    private String passWord;
    private String realName;
}
  • mapper类编写
@Mapper
public interface UserMapper {
    @Select("select * from user")
    public List<User> queryUser();
}
  • service层编写
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public List<User> queryUser(){
        return  userMapper.queryUser();
    }
}
  • controller层编写
@RestController
public class UserController {
   @Autowired
   private UserService serviceUser;
   @RequestMapping("/api/user/all")
   public List<User> queryUser(){
       return serviceUser.queryUser();
   }
}
  • 运行启动类,网页输入http://localhost:8090/api/user/即可通过mybatis访问数据库显示查询结果
    可以看到已经查询数据库的user表信息了

相关文章

网友评论

    本文标题:SpingBoot整合Mybatis示例

    本文链接:https://www.haomeiwen.com/subject/zqxpjhtx.html