我有一个springboot应用程序正在与一个mongo数据库交谈,其中一个集合有点“非结构化”。该集合都与“app config”相关,但不同的应用程序在那里有不同的东西。有些应用程序在顶层只有一些东西,有些具有深层嵌套文档。
如果有一些常见的“顶级”文档,我会有一个类似于@Id String id
的类,然后是Map<String, Object> info
或其他什么,但“灵活”数据在顶层。那么,我可以像使用MongoRepository<Map<String,Object>, String>
之类的东西来扩展MongoRepository吗?有没有更好的方法来处理这样的事情?
答案 0 :(得分:0)
如果你想用springboot构建Rest服务,请按照下面给出的示例代码。这是我在Springboot中找到CRUD的最简单方法
1)使用spring初始化程序下载spring项目(例如:com.library.demo)
2)其余的作为下面的示例代码
<强> application.properties 强>
server.port=8091
spring.data.mongodb.uri=mongodb://localhost:27017/<databaseName>
<强> com.library.demo.model-&GT; Book.java 强>
package com.librarysystem.demo.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="booklist")
public class Book {
@Id
String _id;
String Name;
String ISBN;
String Author;
public Book(String Name,String ISBN,String Author) {
this.Name=Name;
this.ISBN=ISBN;
this.Author=Author;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getAuthor() {
return Author;
}
public void setAuthor(String author) {
Author = author;
}
}
<强> com.library.demo.repository-&GT; BookRepository.java 强>
import com.librarysystem.demo.model.Book;
@Repository
public interface BookRepository extends MongoRepository<Book, String>{
public Book findByName(String BookName);
}
<强> com.library.demo.service-&GT; BookService.java 强>
import com.librarysystem.demo.repository.BookRepository;
@Service
public class BookService {
@Autowired
private BookRepository bookrepository;
public Book create(String Name,String ISBN,String Author) {
return bookrepository.save(new Book(Name,ISBN,Author));
}
public Book getByBookName(String name) {
return bookrepository.findByName(name);
}
public List<Book>getAll(){
return bookrepository.findAll();
}
public void delete(String Name) {
Book b=bookrepository.findByName(Name);
bookrepository.delete(b);
}
}
<强> com.library.demo.controller-&GT; BookController.java 强>
import com.librarysystem.demo.service.BookService;
@RestController
public class BookController {
@Autowired
private BookService bookservice;
@RequestMapping("/create")
public String create(@RequestParam String Name,@RequestParam String ISBN,@RequestParam String Author) {
Book b=bookservice.create(Name, ISBN, Author);
return b.toString();
}
@RequestMapping("/get")
public Book getBook(@RequestParam String Name) {
return bookservice.getByBookName(Name);
}
@RequestMapping("/getAll")
public List getBook() {
return bookservice.getAll();
}
@RequestMapping("/delete")
public String delete(@RequestParam String name) {
bookservice.delete(name);
return "deleted"+name;
}
}
希望这包含您在一个地方需要的一切