一般的Spring Boot项目有四个大包
- pojo:是与数据库表相关的实体类
- controller:接收前端传过来的参数进行操作,之后交给业务层
- service:业务层,不直接对接数据库,只是在这层写接口,有接口之后还需要写接口实现,实现里调用mapper(数据)层
- mapper:写逻辑,对数据库操作
业务需求: 输入用户id,返回用户信息
1、知道数据库表是怎样的,写对应的实体类(pojo层)
就要创建pojo包,在pojo包下创建实体类
package com.walker.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String name;
private Integer age;
private Integer gender;
private String phone;
}
2、写Mapper层,具体实现逻辑或者sql语句
创建mapper包,在mapper包下写该业务mapper
package com.walker.mapper;
import com.walker.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select * from user where id = ${id}")
User findById(Integer id);
}
3、写service接口
创建service包,在service包下写该业务接口
package com.walker.service;
import com.walker.pojo.User;
public interface UserService {
User findById(Integer id);
}
4、实现service接口,并且调用mapper逻辑
在service包下创建实现接口的包(impl),在impl包下写该业务的接口的实现类
package com.walker.service.impl;
import com.walker.mapper.UserMapper;
import com.walker.pojo.User;
import com.walker.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Integer id) {
return userMapper.findById(id);
}
}
5、写controller,接收前端传的参数,调用service(业务)层
创建controller包,在controller包下写该业务
package com.walker.controller;
import com.walker.pojo.User;
import com.walker.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/find")
public User findById(@RequestParam(name="id") Integer id) {
return userService.findById(id);
}
}