Mongo中 |
您所在的位置:网站首页 › 实体类映射数据库字段 › Mongo中 |
_id作为mongo数据库中集合里面每个文档的唯一标识,我们在java中进行增删改查操作中有时候不可避免的需要使用到。但是_id在文档中的定义类型为Objectid类型,那我们在java实体类中又该建立何种类型与之对应呢? 直接新建属性id,类型为String就可以进行操作,增删改成是也能自动转换为_id 实体类: @Data @ApiModel(value="mongoId的测试类") @Document(collection = "test_mongoId") @Component public class TestMongoId { private String id; private String name; private int age; }dao层实现类: @Repository(value = "TestMongoIdDaoImpl") public class TestMongoIdDaoImpl implements TestMongoIdDao { @Resource private MongoTemplate mongoTemplate; @Override public void addTest(TestMongoId testMongoId) { MongoCollection sensorType = mongoTemplate.getCollection("test_mongoId"); sensorType.insertOne(Document.parse(JSON.toJSONString(testMongoId))); } @Override public List findAll() { List mongoIds = mongoTemplate.findAll(TestMongoId.class, "test_mongoId"); return mongoIds; } @Override public TestMongoId findByMongoId(String _id) { Query query = new Query(); query.addCriteria(Criteria.where("_id").is(_id)); TestMongoId testMongoId = mongoTemplate.findOne(query, TestMongoId.class); return testMongoId; } @Override public boolean updateByMongoId(String _id,TestMongoId testMongoId) { Document query = new Document(); query.append("_id", _id); Document document = Document.parse(JSON.toJSONString(testMongoId)); UpdateResult updateResult = mongoTemplate.getCollection("test_mongoId").updateOne(query, new Document("$set",document)); return updateResult.getModifiedCount()>0; } @Override public boolean deleteByMongoId(String _id) { Document query = new Document(); query.append("_id", _id); return mongoTemplate.getCollection(CollectionNameEnum.SENSORTYPEORDER.getValue()).deleteOne(query).getDeletedCount()>0; } }测试类: @RunWith(SpringRunner.class) @SpringBootTest public class TestMongoIdDaoImplTest { @Resource(name= "TestMongoIdDaoImpl") private TestMongoIdDao testMongoIdDaoImpl; @Test public void addTest() { TestMongoId testMongoId = new TestMongoId(); testMongoId.setId("1234564556"); testMongoId.setAge(22); testMongoId.setName("徐渭虎"); // testMongoId.setName("徐风年"); // testMongoId.setAge(18); testMongoIdDaoImpl.addTest(testMongoId); } @Test public void findAll() { List all = testMongoIdDaoImpl.findAll(); System.out.println("all: " + all); } @Test public void findByMongoId() { TestMongoId byMongoId = testMongoIdDaoImpl.findByMongoId("5d48e1a9cfc95a068c6def21"); System.out.println("byMongoId: " + byMongoId); } }测试结果: 添加: 数据库中: 如果将实体中的id改成_id结果依然一样。 @Data @ApiModel(value="mongoId的测试类") @Document(collection = "test_mongoId") @Component public class TestMongoId { private String _id; private String name; private int age; }添加: @Test public void addTest() { TestMongoId testMongoId = new TestMongoId(); testMongoId.set_id("1234564556"); // testMongoId.setAge(22); // testMongoId.setName("徐渭虎"); testMongoId.setName("徐风年"); testMongoId.setAge(18); testMongoIdDaoImpl.addTest(testMongoId); }结果: |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |