spring boot框架搭建-7 建立数据传输对象dto以及映射ModelMapper

对于前后端数据交互的时候,有时候不一定对应上实体类,这时候我们就需要建立dto

package com.example.wx.dto;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Created by w on 2019/3/9.
 */
@Data
@NoArgsConstructor
public class UserDto {
    //用户姓名
    private String name;
    //邮箱
    private String email;
}

使用方式
service

package com.example.wx.service;

import com.example.wx.dto.UserDto;
import com.example.wx.entity.User;

/**
 * Created by w on 2019/2/28.
 */
public interface IUserService {
    //新增一个User
    void saveUser(User user);

    void saveUserDto(UserDto dto);
}

impl

package com.example.wx.service.impl;

import com.example.wx.dto.UserDto;
import com.example.wx.entity.User;
import com.example.wx.repository.UserRepository;
import com.example.wx.service.IUserService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Created by w on 2019/2/28.
 */
@Service
public class UserServiceImpl implements IUserService{
    @Autowired
    UserRepository userRepository;
    @Autowired
    ModelMapper modelMapper;

    @Override
    @Transactional
    public void saveUser(User user) {
        userRepository.save(user);
    }

    @Override
    @Transactional
    public void saveUserDto(UserDto dto) {
        User user = new User();
        //映射
        modelMapper.map(dto,user);
        //新增
        userRepository.save(user);
    }
}

controller

//新增一个UserDto
    @RequestMapping("/saveUserDto")
    public ApiResult saveUserDto(@RequestBody UserDto dto)
    {
        userService.saveUserDto(dto);
        return new ApiResult();
    }

当然ModelMapper使用的时候,需要new一下,或者加一个bean

package com.example.wx.common.bean;

import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by w on 2019/3/1.
 */
@Configuration
public class CommonBean {
    //映射
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}

OK了。
上一篇,spring boot框架搭建-6 链接mysql以及配置jpa
下一篇,spring boot框架搭建-8 springboot配置redis缓存

你可能感兴趣的:(spring,boot框架的搭建与完善,spring,boot从搭建框架到项目实现)