个人笔记
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.2 KiB

3 years ago
# 依赖
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
```
# 配置文件
```properties
# mongodb数据源配置
spring.data.mongodb.uri=mongodb://localhost:27017/open5gs
```
# 代码
- 实体类
```java
@Setter
@Getter
public class Profiles {
@Id
private String id;
private String title;
private List<Pdn> pdn;
private Link ambr;
private Security security;
}
```
- Repository类
<img src="mongo1.png" />
![2](mongo2.png)
```java
@Repository
public interface ProfilesRepository extends MongoRepository<Profiles, String> {
Profiles findByTitle(String title);
@Query(value = "{'_id':{'$ne':null}}", fields = "{'title':1,'_id':0}")
List<Profiles> title();
}
```
- Repository的使用
```java
@Service
public class ProfileService {
@Autowired
private ProfilesRepository profileRepository;
public Page<Profiles> find(Profiles exp, BasePageParam pageParam) {
Integer page = pageParam.getPage();
if (page == null || page < 1) {
page = 1;
}
Integer size = pageParam.getSize();
if (size == null || size == 0) {
size = 20;
}
PageRequest pageable = PageRequest.of(page - 1, size, Direction.DESC, "_id");
ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("_class").withMatcher("title", GenericPropertyMatcher.of(StringMatcher.CONTAINING));
Example<Profiles> example = Example.of(exp, matcher);
return profileRepository.findAll(example, pageable);
}
public Profiles findByTitle(String title) {
return profileRepository.findByTitle(title);
}
public List<Profiles> findTitles() {
return profileRepository.title();
}
public void save(Profiles profiles) throws SprtException {
Profiles old = profileRepository.findByTitle(profiles.getTitle());
if (old != null) {
throw new SprtException("已存在相同名称的模板");
}
profileRepository.save(profiles);
}
public void update(Profiles profiles) throws SprtException {
profileRepository.save(profiles);
}
public void delete(Profiles profiles) {
profileRepository.deleteById(profiles.getId());
}
}
```