1.创建数据库的连接,进行增删改查
(分别为接口和实现类)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
package com.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import com.bean.Company;
@Repository
public class RepositoryImpl implements AbstractRepository {
@Autowired
private MongoTemplate mongoTemplate;
// 查询所有数据
public List<?> findAll(Class<?> entity) {
return mongoTemplate.findAll(entity);
}
// 更新数据
public Company findOne(String id, Class<?> entity) {
return (Company) mongoTemplate.findOne( new Query(Criteria.where( "id" )
.is(id)), entity);
}
// 添加到数据库
public void updateEntity(Company company) {
mongoTemplate.save(company);
}
// 删除选中的数据
public void delete(String id, Class<Company> class1) {
Criteria criteria = Criteria.where( "id" ).in(id);
if (criteria != null ) {
Query query = new Query(criteria);
if (query != null && mongoTemplate.findOne(query, class1) != null )
mongoTemplate.remove(mongoTemplate.findOne(query, class1));
}
}
//增加到数据库
public void insert(Company company) {
mongoTemplate.insert(company);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package com.dao;
import java.util.List;
import com.bean.Company;
public interface AbstractRepository {
public List<?> findAll(Class<?> entity);
public Company findOne(String id,Class<?> entity);
public void updateEntity(Company company);
public void delete(String id, Class<Company> class1);
public void insert(Company company);
}
|
总结:与关系型数据库的连接一样,没有什么区别。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:https://my.oschina.net/zhangzexing/blog/907223