美文网首页
mongodb(mongotemplate)不使用objectI

mongodb(mongotemplate)不使用objectI

作者: 不知不怪 | 来源:发表于2022-01-14 17:20 被阅读0次

    1 指定主键类型: @MongoId(targetType = FieldType.STRING)

    package com.gzz;
    
    import org.springframework.data.mongodb.core.mapping.Document;
    import org.springframework.data.mongodb.core.mapping.FieldType;
    import org.springframework.data.mongodb.core.mapping.MongoId;
    
    import lombok.AllArgsConstructor;
    import lombok.Builder;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @Document("user")
    public class User {
        @MongoId(targetType = FieldType.STRING)
        private String id;
        private String name;
        private Integer age;
    
    }
    

    2 提前给定主键: org.bson.types.ObjectId && ObjectId.get().toString()

    
    package com.gzz;
    
    import java.util.List;
    
    import javax.annotation.PostConstruct;
    
    import org.bson.types.ObjectId;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import static org.springframework.data.mongodb.core.query.Criteria.where;
    import static org.springframework.data.mongodb.core.query.Query.query;
    import lombok.extern.slf4j.Slf4j;
    
    @Slf4j
    @SpringBootApplication
    public class Application3 {
        public static void main(String[] args) {
            SpringApplication.run(Application3.class, args);
        }
    
        @Autowired
        private MongoTemplate mongoTemplate;
    
        @PostConstruct
        public void init() {
            User user1 = User.builder().id(ObjectId.get().toString()).name("张三").age(12).build();
            User user2 = User.builder().id(ObjectId.get().toString()).name("李四").age(14).build();
            User user3 = User.builder().id(ObjectId.get().toString()).name("王五").age(15).build();
            mongoTemplate.insert(List.of(user1, user2, user3), User.class);
            User user = mongoTemplate.findOne(query(where("_id").is("61e139e4531fde11308e9fca")), User.class);
            log.info("user={}",user);
        }
    
    }

    相关文章

      网友评论

          本文标题:mongodb(mongotemplate)不使用objectI

          本文链接:https://www.haomeiwen.com/subject/rsaacrtx.html