1.自定义Repository方式
1.1pom.xml配置
<!-- mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
image.png
1.2项目目录
image.png
1.3User.java
package com.shuai.spring_boot_1.domain;
import org.springframework.data.annotation.Id;
public class User {
//id属性是给mongodb用的,用@Id注解修饰
@Id
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
image.png
1.4UserRepository.java
package com.shuai.spring_boot_1.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.shuai.spring_boot_1.domain.User;
public interface UserRepository extends MongoRepository<User, String> {
User findByName(String name);
}
image.png
1.5OneController.java
package com.shuai.spring_boot_1.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.shuai.spring_boot_1.dao.UserRepository;
import com.shuai.spring_boot_1.domain.User;
@RestController
public class OneController {
@Autowired
UserRepository userRepository;
@RequestMapping("/save")
public String save(){
User user = new User();
user.setId("1");
user.setName("张三");
user.setAge(10);
userRepository.save(user);
System.out.println("保存成功");
return "ok";
}
@RequestMapping("/find")
public String find(){
List<User> findAll = userRepository.findAll();
System.out.println(findAll);
return "ok";
}
@RequestMapping("/findByName")
public String findByName(){
User findByName = userRepository.findByName("张三");
System.out.println(findByName);
return "ok";
}
}
image.png
1.6App.java
package com.shuai.spring_boot_1;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
image.png
1.7运行项目
运行App.java中的main方法
1.8访问项目
http://localhost:8080/save 保存
http://localhost:8080/find 获取全部
http://localhost:8080/findByName 通过名字获得
网友评论