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缓存

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值