2017-10-21 104 views
0

我有一個簡單春數據休息實現使用休眠MongoDB的用戶創建的。條目創建返回201,但訪問它返回404

User.java

@Data 
@Entity 
@RequiredArgsConstructor 
@JsonIgnoreProperties(ignoreUnknown = true) 
public class User { 

    private @Id String username; 

    private String about; 
} 

UserRepository.java

@PreAuthorize("hasRole('ROLE_USER')") 
@CrossOrigin(methods = {GET, PUT, POST}) 
public interface UserRepository extends MongoRepository<User, String> { 

    @Override 
    @PreAuthorize("hasRole('ROLE_ADMIN')") 
    <S extends User> S save(S s); 
} 

然後我做一個POST調用/users這身搭配:

{ 
    "username": "username1", 
    "about": "example" 
} 

我得到一個201 Created響應與以下機構:

{ 
    "about": "example", 
    "_links": { 
     "self": { 
      "href": "http://localhost:8080/api/users/username1" 
     }, 
     "user": { 
      "href": "http://localhost:8080/api/users/username1" 
     } 
    } 
} 

我做GET請求/users,看是否確實添加了用戶並返回此響應是理所當然的:

{ 
    "_embedded": { 
     "users": [ 
      { 
       "about": "example", 
       "_links": { 
        "self": { 
         "href": "http://localhost:8080/api/users/username1" 
        }, 
        "user": { 
         "href": "http://localhost:8080/api/users/username1" 
        } 
       } 
      } 
     ] 
    }, 
    "_links": { 
     "self": { 
      "href": "http://localhost:8080/api/users{?page,size,sort}", 
      "templated": true 
     }, 
     "profile": { 
      "href": "http://localhost:8080/api/profile/users" 
     } 
    }, 
    "page": { 
     "size": 20, 
     "totalElements": 1, 
     "totalPages": 1, 
     "number": 0 
    } 
} 

的問題

但後來我訪問鏈接中提供的用戶的URL,即http://localhost:8080/api/users/username1,但我得到一個404 Not Found響應。

我在做什麼錯?我試過看例子和文檔,但似乎沒有做這項工作。如果我添加@AutoGenerated註釋它可以工作,但我顯然希望id由請求提供爲username

回答

0

User.java,我改變了username的聲明如下:

@Id 
@JsonProperty("username") 
@NotBlank 
private String id; 

MongoDB的要求_id作爲默認每個文件,否則它不會得到索引的主鍵。我必須將字段名稱更改爲id,以便在MongoDB上轉換爲_id,並使用@Id註釋。爲了解決這個問題,我使用@JsonProperty("username")來獲取請求的JSON主體的username屬性的值。