新建service、impl、model目录。
image.png
在UserPasswordDOMapper新增方法。
UserPasswordDO selectByUserId(Integer userId);
在UserPasswordDOMapper.xml新增如下代码:
<select id="selectByUserId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user_password
where user_id = #{id,jdbcType=INTEGER}
</select>
创建UserModel
@Data
public class UserModel {
private Integer id;
private String name;
private Byte gender;
private Integer age;
private String telphone;
private String registerMode;
private String thirdPartyId;
private String encrptPassword;
}
如果@Data报错,请在pom文件引入lombok依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
创建UserService
public interface UserService {
//通过对象id获取对象
UserModel getUserById(Integer id);
}
UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDOMapper userDOMapper;
@Autowired
private UserPasswordDOMapper userPasswordDOMapper;
//为什么不直接返回
@Override
public UserModel getUserById(Integer id) {
//调用userdomapper获取到dataobject
UserDO userDO = userDOMapper.selectByPrimaryKey(id);
if (userDO == null) {
return null;
}
//通过用户id获取用户加密密码信息
UserPasswordDO userPasswordDO = userPasswordDOMapper.selectByUserId(userDO.getId());
return convertFromDataObject(userDO, userPasswordDO);
}
private UserModel convertFromDataObject(UserDO userDO, UserPasswordDO userPasswordDO) {
if (userDO == null) {
return null;
}
UserModel userModel = new UserModel();
BeanUtils.copyProperties(userDO, userModel);
if (userPasswordDO != null) {
userModel.setEncrptPassword(userPasswordDO.getEncrptPassword());
}
return userModel;
}
}
创建controller和返回对象目录viewobject
创建返回对象UserVo
@Data
public class UserVo {
private Integer id;
private String name;
private Byte gender;
private Integer age;
private String telphone;
}
创建UserController
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/get")
public UserVo getUser(@RequestParam(name = "id") Integer id){
//调用service服务获取对应id对象返回给前端
UserModel userModel = userService.getUserById(id);
//将核心领域模型用户对象转换为可供UI使用的viewobject
UserVo userVo = convertFromMode(userModel);
return userVo;
}
private UserVo convertFromMode(UserModel userModel) {
if (userModel == null) {
return null;
}
UserVo userVo = new UserVo();
BeanUtils.copyProperties(userModel, userVo);
return userVo;
}
}
请求地址:http://localhost:8080/user/get?id=6
返回值:{"id":6,"name":"test","gender":1,"age":22,"telphone":"12312312311"}
网友评论