简体   繁体   中英

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

I have to create a very simple Spring "market" app.

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

//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.

example for interacting with items endpoints: create: {id:1 name:"Item1", ownerId:1} ;

getAllItems with ownerId = 1 (use single query)

[

   {

      "id":3,

      "name":”Item1”,

      "ownerId":1,

      “ownerUsername”:"User1"

   }

]

Example:

"User1" owns "Item1". He wants to sell it for $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". The contract is now closed. "User1" receives $100 in his account. "User2" is the new owner of "Item1".

Contracts:

contract entity attributes: id, sellerId, buyerId, itemId, price,status. (The seller is the owner of the item and can not be the buyer) endpoints - CRUD. Example for interacting with contracts endpoints:

create: {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:

{

  "sellerId":1,

  "itemId":3,

  "price":100,

  "active":true

}

update price of active contract by id: {"itemId":3, "price":200}

getAllActive contracts (use single native query):

[

   {

      "sellerId":1,

      “sellerUsername”:"User1",

      "itemId":3,

      "price":200,

      "active":true

   }

]

closing active contract by id {"itemId":3, "buyerId":2} .

Expected behavior: update the accounts of users with id 1 and id 2.

getAllClosed contracts by optional parameters: itemId, sellerId, buyerId (use single native query):

[

   {

"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.

like this (just user domain)

UserService (service layer)

@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)

@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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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