Introduction of depend on
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>Copy the code
Write entity
package com.gavin.exer.entity;
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
@Data
@Document(indexName = "users")
public class User {
private int id;
private String username;
private String password;
private int age;
/** getter and setter */
}
Copy the code
Write the DAO
package com.gavin.exer.mapper;
import com.gavin.exer.entity.User;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface UserDao extends ElasticsearchRepository<User, Integer> {
}
Copy the code
Writing the Controller
package com.gavin.exer.controller; import com.gavin.exer.entity.User; import com.gavin.exer.mapper.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired UserDao userDao; @PostMapping("/addUser") public String addUser(String username, String password, Integer age) { User user = new User(); user.setUsername(username); user.setPassword(password); user.setAge(age); return String.valueOf(userDao.save(user).getId()); } @deletemapping ("/deleteUser") public String deleteUser(Integer id) {userdao.deleteById (id); return "Success!" ; } @PutMapping("/updateUser") public String updateUser(Integer id, String username, String password, Integer age) { User user = new User(); user.setId(id); user.setUsername(username); user.setPassword(password); user.setAge(age); return String.valueOf(userDao.save(user).getId()); } @getMapping ("/getUser") public User getUser(Integer ID) {return userdao.findById (id).get(); } @GetMapping("/getAllUsers") public Iterable<User> getAllUsers() { return userDao.findAll(); }}Copy the code
Postman test
POST http://localhost:8080/addUser? username=”gavin”&password=”gavin”&age=10
PUT http://localhost:8080/updateUser? username=”gavin”&password=”gavin”&age=10&id=1
GET http://localhost:8080/getAllUsers
GET http://localhost:8080/getUser? id=0
Refer to the article
Es springboot:zhuanlan.zhihu.com/p/54384152
Es rest HTTP access: cloud.tencent.com/developer/a…
Es the HTTP API tutorial: www.yiibai.com/elasticsear…