如何在休息服务器中添加和编辑用户

时间:2016-05-23 10:35:24

标签: java spring-boot

我有一个简单的休息服务器。我可以从数据库中看到所有用户,并按ID或名称查找用户。

@RepositoryRestResource(collectionResourceRel = "admin", path = "admins")
public interface AdminRepository extends PagingAndSortingRepository<Admin, Long>{

    List<Admin> findByName(@Param("name") String name);

    @Query("SELECT a.name from Admin a where a.id = :id")
    Admin findNameById(@Param("id") Long id);
}

如何添加和编辑用户?

2 个答案:

答案 0 :(得分:0)

Spring存储库有预定义的方法来保存,更新和删除,所以我们可以使用它们,但是为了使用它们,我们需要在类中注入存储库,如下所示:

import org.springframework.beans.factory.annotation.Autowired;

public class AdminResource {

    @Autowired // inject the Repository in the class
    private AdminRepository adminRepository;

    public void createAdmin(Admin admin) {

        adminRepository.save(admin);// same you can use for update
    }

    public void deleteAdmin(Admin admin) {
            adminRepository.delete(admin);
    }

}

答案 1 :(得分:0)

要更新记录,您可以使用对象的项目资源URL,例如http://localhost:8080/admins/1并向其发送PUT请求,其中包含对象的JSON表示作为请求正文,如下所示:

PUT http://localhost:8080/admins/1

{
  "name": "New name"
}

要创建新对象,请对集合URL使用POST请求(例如http://localhost:8080/admins)。相同的规则适用于请求正文:

POST http://localhost:8080/admins

{
  "name": "Name of new object"
}

默认情况下可以访问这些操作,不需要编写其他代码。

相关文档:

请注意,由于您正在使用HATEOAS,因此确定项目资源URL(用于更新对象)的正确方法是转到集合,因为此资源还包含指向其他资源的链接,例如:

{
  "_embedded" : {
    "admin" : [ {
      "name" : "Test 1 2 3 4",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/admins/1"
        },
        "admin" : {
          "href" : "http://localhost:8080/admins/1"
        }
      }
    }, ...]
  }
}

在这种情况下,属性_links.self.href包含对项目资源URL的引用,您应该将其用于更新。