如何使用Spring框架和MongoDb

时间:2019-01-13 18:45:44

标签: java spring mongodb rest

我正在使用一个已经存在的mongoDB数据库,在某些情况下,该数据库使用其ObjectId参考来引用另一个馆藏的文档:

{
  _id:ObjectId(...),
  ...
  homeTeam:ObjectId(...),
  visitorTeam:ObjectI(...),
  ...
}

但是当我尝试通过其余的GET方法检索数据时,我得到的只是一个例外:没有找到能够将类型[org.bson.types.ObjectId]转换为类型[nbaApiRest.domain.Team]的转换器。

我尝试使用@DBRef注释,但是问题仍然存在。

这是我的Game文档模型:

@Data
@Document(collection="games")
@JsonInclude(Include.NON_NULL)
public class Game {

    @Id
    private final String id;
    private final LocalDateTime date;
    @DBRef
    private final Team homeTeam;
    @DBRef
    private final Team visitorTeam;
    private final int homePoints;
    private final int visitorPoints;
    private final int attendance;
}

这是我的嵌套Team对象的模型,该模型由mongoDB中Game文档中的ObjectId引用:

@Data
@Document(collection="teams")
@JsonInclude(Include.NON_NULL)
public class Team{

    @Id
    private final String id;
    private final String name;
    private final int from;
    private final String code;
    private final List<Franchise> stages;
}

在每个模型中,我根据spring tutorial定义了一个基本的存储库,该存储库对Team正常,但对Game无效:

@RepositoryRestResource(collectionResourceRel = "teams", path =    "teams")
public interface TeamRepository extends MongoRepository<Team, String> {

public Team findById(ObjectId id);

    // Prevents POST /teams and PATCH /teams/:id 
    @SuppressWarnings("unchecked")
    @Override 
    @RestResource(exported = false) 
    public Team save(Team t); 

    // Prevents DELETE /teams/:id 
    @Override 
    @RestResource(exported = false) 
    public void delete(Team t); 
}

@RepositoryRestResource(collectionResourceRel = "games", path = "games")
public interface GameRepository extends MongoRepository<Game, String> {

// Prevents POST /games and PATCH /games/:id 
    @SuppressWarnings("unchecked")
    @Override 
    @RestResource(exported = false) 
    public Game save(Game g); 

    // Prevents DELETE /games/:id 
    @Override 
    @RestResource(exported = false) 
    public void delete(Game g); 
 }

我希望在注入两个Team文档的情况下获得请求的Game文档作为GET响应,但是我无法设法将那些ObjectId转换为Team文档。

0 个答案:

没有答案