springboot

SpingBoot整合Mybatis示例

2020-03-12  本文已影响0人  Coding测试

以下示例非常适合新人练手
本章项目源码下载地址:https://github.com/rootczy/spingboot-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;

添加两条测试数据如下:


@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
public interface UserMapper {
    @Select("select * from user")
    public List<User> queryUser();
}
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    public List<User> queryUser(){
        return  userMapper.queryUser();
    }
}
@RestController
public class UserController {
   @Autowired
   private UserService serviceUser;
   @RequestMapping("/api/user/all")
   public List<User> queryUser(){
       return serviceUser.queryUser();
   }
}

上一篇 下一篇

猜你喜欢

热点阅读