MongoDB入门

第一:mongo依赖


    org.springframework.boot
    spring-boot-starter-data-mongodb

第二:mongo配置

server:
  port: 9998
spring:
  data:
    mongodb:
      host: 192.168.140.100
      port: 27017
      database: green-history

 第三:映射

import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;
import java.util.Date;

/**
 * 

* 联想词表 *

* * @author itheima */ @Data @Document("ap_associate_words") public class ApAssociateWords implements Serializable { private static final long serialVersionUID = 1L; private String id; /** * 联想词 */ private String associateWords; /** * 创建时间 */ private Date createdTime; }

核心方法

@SpringBootTest(classes = MongoApplication.class)
@RunWith(SpringRunner.class)
public class MongoTest {


    @Autowired
    private MongoTemplate mongoTemplate;

    //保存
    @Test
    public void saveTest(){
        for (int i = 0; i < 10; i++) {
            ApAssociateWords apAssociateWords = new ApAssociateWords();
            apAssociateWords.setAssociateWords("MongoDB入门");
            apAssociateWords.setCreatedTime(new Date());
            mongoTemplate.save(apAssociateWords);
        }
    }

    //查询一个
    @Test
    public void saveFindOne(){
        ApAssociateWords apAssociateWords = mongoTemplate.findById("65bbac06cf54d73f36b16e59", ApAssociateWords.class);
        System.out.println(apAssociateWords);
    }

    //条件查询
    @Test
    public void testQuery(){
        Query query = Query.query(Criteria.where("associateWords").is("MongoDB入门"))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List apAssociateWordsList = mongoTemplate.find(query, ApAssociateWords.class);
        System.out.println(apAssociateWordsList);
    }

    //删除
    @Test
    public void testDel(){
        mongoTemplate.remove(Query.query(Criteria.where("associateWords").is("MongoDB入门")),ApAssociateWords.class);
    }
}

你可能感兴趣的:(mongodb,数据库)