Our Spring POST Lesson with Database Definitions.
Link to IMG: https://ibb.co/dmJMqJD
GET /users
GET /users/123
–> This is the IDPOST
request to /users
with a JSON payload containing the necessary user information.PUT
request to /users/123
with a JSON payload containing the updated information.DELETE
request to /users/123
.@Controller
@RequestMapping("/mvc/person")
public class PersonViewController {
// Autowired enables Control to connect HTML and POJO Object to database easily for CRUD
@Autowired
private PersonDetailsService repository;
@GetMapping("/read")
public String person(Model model) {
List<Person> list = repository.listAll();
model.addAttribute("list", list);
return "person/read";
}
/* The HTML template Forms and PersonForm attributes are bound
@return - template for person form
@param - Person Class
*/
@GetMapping("/create")
public String personAdd(Person person) {
return "person/create";
}
/* Gathers the attributes filled out in the form, tests for and retrieves validation error
@param - Person object with @Valid
@param - BindingResult object
*/
@PostMapping("/create")
public String personSave(@Valid Person person, BindingResult bindingResult) {
// Validation of Decorated PersonForm attributes
if (bindingResult.hasErrors()) {
return "person/create";
}
repository.save(person);
repository.addRoleToPerson(person.getEmail(), "ROLE_STUDENT");
// Redirect to next step
return "redirect:/mvc/person/read";
}
@GetMapping("/update/{id}")
public String personUpdate(@PathVariable("id") int id, Model model) {
model.addAttribute("person", repository.get(id));
return "person/update";
}
@PostMapping("/update")
public String personUpdateSave(@Valid Person person, BindingResult bindingResult) {
// Validation of Decorated PersonForm attributes
if (bindingResult.hasErrors()) {
return "person/update";
}
repository.save(person);
repository.addRoleToPerson(person.getEmail(), "ROLE_STUDENT");
// Redirect to next step
return "redirect:/mvc/person/read";
}
@GetMapping("/delete/{id}")
public String personDelete(@PathVariable("id") long id) {
repository.delete(id);
return "redirect:/mvc/person/read";
}
@GetMapping("/search")
public String person() {
return "person/search";
}
}
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Convert;
import org.hibernate.annotations.Type;
@Entity
public class UserStats {
@Id
private Long id;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private Map<String, Map<String, Object>> stats = new HashMap<>();
// Standard getters and setters
}
# Integration with Java Backend
## POJO and Database Interaction
- **What is a POJO?**
- POJO stands for Plain Old Java Object.
- It's a Java object not bound by any restriction other than those forced by the Java Language Specification.
- **Role in Database Interaction**:
- POJOs are used to encapsulate data and represent database entities in object-oriented programming.
- They interact with databases through Object-Relational Mapping (ORM) frameworks like Hibernate.
#### Defining a POJO with JSONB Field
```java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Convert;
import java.util.Map;
import java.util.HashMap;
import org.hibernate.annotations.Type;
@Entity
public class User {
@Id
private Long id;
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private Map<String, Map<String, Object>> additionalProperties = new HashMap<>();
// Standard getters and setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Map<String, Map<String, Object>> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(Map<String, Map<String, Object>> additionalProperties) {
this.additionalProperties = additionalProperties;
}
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByLastName(String lastName);
Optional<User> findByEmail(String email);
List<User> findByAgeGreaterThan(int age);
}
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
public class UserStatsService {
@PersistenceContext
private EntityManager entityManager;
// Create
@Transactional
public void createUserStat(UserStats userStat) {
entityManager.persist(userStat);
}
// Read
public UserStats getUserStat(Long id) {
return entityManager.find(UserStats.class, id);
}
// Update
@Transactional
public void updateUserStat(Long id, Map<String, Map<String, Object>> newStats) {
UserStats userStat = getUserStat(id);
if (userStat != null) {
userStat.setStats(newStats);
entityManager.merge(userStat);
}
}
// Delete
@Transactional
public void deleteUserStat(Long id) {
UserStats userStat = getUserStat(id);
if (userStat != null) {
entityManager.remove(userStat);
}
}
}
# Example Code with all Rest API Methods
```Java
// User model class representing the user entity
public class User {
private Long id;
private String username;
private String email;
// other fields, getters, setters
}
// UserController class handling user-related API requests
@RestController //handles HTTP requests and produces JSON responses.
@RequestMapping("/users")
public class UserController {
// Service for handling user-related operations
@Autowired
private UserService userService;
// GET: Retrieve a list of users (read)
@GetMapping
public ResponseEntity<List<User>> getUsers() {
List<User> users = userService.getAllUsers();
return new ResponseEntity<>(users, HttpStatus.OK);
}
// GET: Fetch a single user by ID (read)
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
return new ResponseEntity<>(user, HttpStatus.OK);
}
// POST: Create a new user (Create)
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User newUser) {
User createdUser = userService.createUser(newUser);
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
}
// PUT: Update an existing user by ID (Update)
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
User user = userService.updateUser(id, updatedUser);
return new ResponseEntity<>(user, HttpStatus.OK);
}
// DELETE: Remove a user by ID (Delete)
@DeleteMapping("/{id}")
public ResponseEntity<String> deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return new ResponseEntity<>("User deleted successfully", HttpStatus.OK);
}
}
// UserService interface defining user-related operations
public interface UserService { //declares all 5 methods of CRUD
List<User> getAllUsers();
User getUserById(Long id);
User createUser(User user);
User updateUser(Long id, User updatedUser);
void deleteUser(Long id);
}