简体   繁体   English

我应该如何使用 REST API 创建这个项目?

[英]How should I go about creating this project using REST API?

I have to create a very simple Spring "market" app.我必须创建一个非常简单的 Spring“市场”应用程序。

No front-end needed无需前端

The Market:市场:

The system must operate as a simplified market where users can be buyers or sellers.该系统必须作为一个简化的市场运行,用户可以是买家或卖家。

Users:用户:

user entity attributes: id:1, username:"User1", account:0用户实体属性:id:1, username:"User1", account:0

//account just gets incremented with each entry in the database. //帐户只是随着数据库中的每个条目而增加。

The users can buy and sell items.用户可以买卖物品。

Items:项目:

item entity attributes: id:3, name:Item1, ownerId:1.项目实体属性:id:3、name:Item1、ownerId:1。

example for interacting with items endpoints: create: {id:1 name:"Item1", ownerId:1} ;与项目端点交互的示例: create: {id:1 name:"Item1", ownerId:1} ;

getAllItems with ownerId = 1 (use single query)拥有 ownerId = 1 的 getAllItems(使用单个查询)

[

   {

      "id":3,

      "name":”Item1”,

      "ownerId":1,

      “ownerUsername”:"User1"

   }

]

Example:例子:

"User1" owns "Item1". “用户 1”拥有“项目 1”。 He wants to sell it for $100.他想以 100 美元的价格出售它。 He creates an active contract.他创建了一个有效的合同。 Other users can review all active contracts and choose to participate.其他用户可以查看所有有效合约并选择参与。 "User2" has enough money in her account and buys "Item1". “User2”在她的帐户中有足够的钱并购买“Item1”。 The contract is now closed.合同现已关闭。 "User1" receives $100 in his account. “用户 1”在他的帐户中收到 100 美元。 "User2" is the new owner of "Item1". “User2”是“Item1”的新所有者。

Contracts:合同:

contract entity attributes: id, sellerId, buyerId, itemId, price,status.合约实体属性:id、sellerId、buyerId、itemId、price、status。 (The seller is the owner of the item and can not be the buyer) endpoints - CRUD. (卖方是物品的所有者,不能是买方)端点 - CRUD。 Example for interacting with contracts endpoints:与合约端点交互的示例:

create: {itemId: 3, price: 100} .创建: {itemId: 3, price: 100} Expected behavior: find the owner of item with id 3 in the DB (ownerId = 1) persist the new active contract in the DB:预期行为:在数据库中找到 id 为 3 的项目的所有者(ownerId = 1),将新的活动合约持久保存在数据库中:

{ {

  "sellerId":1,

  "itemId":3,

  "price":100,

  "active":true

} }

update price of active contract by id: {"itemId":3, "price":200}通过 id 更新有效合约的价格: {"itemId":3, "price":200}

getAllActive contracts (use single native query): getAllActive 合约(使用单个本机查询):

[

   {

      "sellerId":1,

      “sellerUsername”:"User1",

      "itemId":3,

      "price":200,

      "active":true

   }

]

closing active contract by id {"itemId":3, "buyerId":2} .通过 id {"itemId":3, "buyerId":2}关闭有效合约。

Expected behavior: update the accounts of users with id 1 and id 2.预期行为:更新 id 1 和 id 2 用户的帐户。

getAllClosed contracts by optional parameters: itemId, sellerId, buyerId (use single native query):通过可选参数 getAllClosed 合约:itemId、sellerId、buyerId(使用单个原生查询):

[

   {

"sellerId":1,

“sellerUsername”:"User1",

"buyerId":2,

“buyerUsername”:"User2",

 "itemId":3,

 "price":100,

 "active":false

   }

]

So far, these are my Entities:到目前为止,这些是我的实体:

BaseEntity:基本实体:

@MappedSuperclass
public abstract class BaseEntity {

    private Long id;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

Users:用户:

@Entity
@Table(name = "users")
public class User extends BaseEntity{

    private String username;
    private Long account;
    private Set<Item> items;

    public User() {
    }


    @Column(name = "username", nullable = false)
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "account", nullable = false)
    public Long getAccount() {
        return account;
    }

    public void setAccount(Long account) {
        this.account = account;
    }

    @OneToMany(mappedBy = "id")
    public Set<Item> getItems() {
        return items;
    }

    public void setItems(Set<Item> items) {
        this.items = items;
    }
}

Items:项目:

@Entity
@Table(name = "items")
public class Item extends BaseEntity{

    private String name;
    private String ownerUsername;
    private User user;

    public Item() {
    }


    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //get the id of the item's owner
    @ManyToOne
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }


    public String getOwnerUsername() {
        return user.getUsername();
    }

    public void setOwnerUsername(String ownerUsername) {
        this.ownerUsername = ownerUsername;
    }
}

So, what should I do from here on?那么,从这里开始我该怎么办?

If you've already created persistence layers (using Spring Data JPA or another mapper), You need to develop service logic and create a presentation layer.如果您已经创建了持久层(使用 Spring 数据 JPA 或其他映射器),则需要开发服务逻辑并创建表示层。

like this (just user domain)像这样(只是用户域)

UserService (service layer) UserService(服务层)

@Service
@RequiredArgsConstructor
public class UserService {

  private final UserJpaRepository repository;

    @Transactional
  public Long createUser(String username) {
        User user = new User();
        user.setUsername(username);
        // other logic ...
        repository.save(user);

        return user.getId();
    }

    @Transactional(readonly = true)
    public User getUser(Long id) {
        return repository.findById(id)
                            .orElseThrow(() -> IllegalArgumentsException("Not Found Entity."))
    }

}

UserAPIController (presentation layer) UserAPIController(表示层)

@RestController
@RequiredArgsConstructor
public class UserAPIController {

    private final UserService userService;

    @PostMapping("/users")
    public ResponseEntity<Long> createUser(@RequestBody CreateUserDTO dto) {
        Long userId = userService.createUser(dto.getUsername());
        return new ResponseEntity(userId, HttpStatus.CREATED);
    }

    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        User user = userService.getUser(id);
        return new ResponseEntity(user, HttpStatus.OK);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM