SpringBoot基础-入门项目

创建项目

创建Spring Boot项目

项目整体目录  

  • java 

①controller层:控制层 ,负责方法调用

②entity层:实体层,存放Java Bean(属性+get,set,toString方法)

③mapper层:与resources中的mapper对接

④service层:业务层,处理各种业务

⑤Application类:相当于整个项目的主(main)方法

  • resources

SpringBoot基础-入门项目_第1张图片

①mapper:存放Mapper.xml文件,与数据库有关

②application.properties:是Spring Boot的配置文件

SpringBoot整合SpringMVC

①打开pom.xml,引入SpringMVC依赖,把下面一段代码放到标签里面(不能覆盖里面的其他代码),CTRL+SHIFT+O刷新依赖

        
            org.springframework.boot
            spring-boot-starter-web
        

SpringBoot整合Mybatis

①打开pom.xml,引入Mybatis依赖,把下面一段代码放到标签里面(不能覆盖里面的其他代码),CTRL+SHIFT+O刷新依赖

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.1
        
        
            mysql
            mysql-connector-java
            runtime
        

②更改配置文件application的扩展名为.yml或.yaml一般使用.yml/.yaml,因为冗余度低,好操作,易用

SpringBoot基础-入门项目_第2张图片

 ③编写配置文件

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/QCBY_DB?useUnicode=true&characterEncoding=utf-8
    username: root
    password: 密码
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:mapper/*.xml  #对应resources/mapper映射xml文件所在路径
  type-aliases-package: com.qcby.entity  #对应实体类路径

实践测试 

①数据库创建user表,插入数据

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

②在entity包中,创建User实体类

public class User {
    private Long id;
    private String name;

    //get,set,toString方法
}

③在mapper包下创建UserMapper接口,加上@Mapper注解

@Mapper
public interface UserMapper {

}

④在resources/mapper目录下创建UserMapper.xml文件,查询数据库中数据




    

⑤编写UserMapper接口

@Mapper
public interface UserMapper {
    public List findAll();
}

⑥在service包下,创建UserService接口

public interface UserService {
    public List findAll();
}

⑦在service包下创建impl包,再创建UserServiceImpl类,继承UserService接口,加上@Service注解

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public List findAll(){
        return this.userMapper.findAll();
    }
}

⑧在controller包下,创建UserController类,加上@RestController注解

@RestController//等价于@Controller + @ResponseBody
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserServiceImpl service;

    @RequestMapping("findAll")
    public List findAll(){
        return this.service.findAll();
    }
}

⑨编辑SpringBootProjectApplication类,添加@MapperScan注解

@MapperScan("com.qcby.mapper")
@SpringBootApplication
public class SpringBootProjectApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootProjectApplication.class, args);
    }

}

⑩启动项目,在浏览器中访问 http://localhost:8080/user/findAll

SpringBoot基础-入门项目_第3张图片

你可能感兴趣的:(Spring,Boot,spring,boot,java,spring)