如何保存与用户相关联的订单详细信息,以及如何根据url参数返回与用户详细信息相关联的订单数据?

时间:2019-04-05 19:17:30

标签: spring spring-boot spring-data

我已经将User和Order实体创建为波纹管。我要实现的是http://localhost:8080/users/username吗?给出了我只想根据提供的用户名返回用户详细信息。如果http://localhost:8080/users/username?detail=true,我想返回用户详细信息和所提供用户名的订单详细信息。我该如何实现?

User.java

commitOffsetsInFinalize

Order.java

@Entity
public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private long id;
   private String userName;
   private String password;
   private String firstName;
   private String lastName;
   private String gender;
   private String lastLoggedIn;
   @OneToMany
   List<Order> listOfOrder;

   //constructors
   //getter and setter

}

@Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; private float amount; private String createdAt; private String deliveredDate; //constructors //getter and setter }

Controller.java

UserRepository

//CREATE CUSTOMER
@RequestMapping(method = POST, value = "/create")
public ResponseEntity createCustomerDetails(@RequestParam String userName, String password, String firstName,
                                            String lastName, String gender) {
    String lastLogged = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
    User user = new User(userName, password, firstName, lastName, gender, lastLogged);
    userRepository.save(user);
    return ResponseEntity.status(OK).body(user.getId() + " User were successfully saved");
}

//CREATE ORDER
@RequestMapping(method = POST, value = "/order/{userName}")
public ResponseEntity createOrder(@PathVariable ("userName") String userName, @RequestParam float amount)
{
    String createdAt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
    String deliveredDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
    User user = orderService.findUser(userName);
    if (!user.equals(null))
    {
        Order order = new Order(amount,createdAt,deliveredDate);
        user.getListOfOrder().add(order);
        return ResponseEntity.status(OK).body("order details were saved under "+user.getUserName() + " "+user.getFirstName());
    }

    return ResponseEntity.status(NOT_FOUND).body(null + " was not found");

}

   //GET THE USER DETAILS
@RequestMapping(method = GET, value = "/users/{userName}")
public ResponseEntity getUserDetail(@PathVariable("userName") String userName,
                                          @RequestParam(defaultValue ="none", required = false) String detail) {
    if (!detail.equals("none")){
        return .....;
    }else { 

        return ........;
    }
}

1 个答案:

答案 0 :(得分:1)

如果可以手动进行序列化,则可以使用JsonView确定要序列化的内容。

https://www.baeldung.com/jackson-json-view-annotation

User.java

import com.fasterxml.jackson.annotation.JsonView;

public class User {

    @JsonView(Views.Lite.class)
    private String name;

    @JsonView(Views.Full.class)
    private List<Order> orders;

}

Views.java

public class Views {

    public static class Lite {}

    public static class Full extends Lite {}

}

UserController.java

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ObjectMapper mapper;

    @GetMapping("/user/{username}")
    public ResponseEntity<String> getUserDetail(@PathVariable String username, @RequestParam(required = false) String detail) throws JsonProcessingException {
        User user = userRepository.findByUserName(username);
        Class viewClass = Views.Lite.class;
        if (!StringUtils.isEmpty(detail)) {
            viewClass = Views.Full.class;
        }
        return ResponseEntity.status(HttpStatus.OK)
                    .body(mapper.writerWithView(viewClass).writeValueAsString(user));
   }
}