Spring Components
Controller
- Handle HTTP methods
- Keep them as simple as possible
@RestController
is a child of @Controller
- @RestController automatically converts json to pojo
@Controller
@RequestMapping("/customer") // Handles any method, GET, POST, PATCH, etc
public class CustomerController {
@Autowired
private CustomerDAO customerDAO; // scans all components that implements this interface and picks the first
// @RequestMapping(path="/list",method=RequestMethod.GET)
@GetMapping("/list")
public String listCustomers(Model model) {
List<Customer> customers = customerDAO.getCustomers();
model.addAttribute("customers", customers); // model for display
return "list-customers";
}
}
Service
Service Facade
design pattern
- Intermediate layer for custom business logic
- Integrate data from multiple sources (DAO/repositories)
- It's a good practice to start and commit transactions on the service layer
public interface CustomerService {
public List<Customer> getCustomers();
public void saveCustomer(Customer customer);
}
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerDAO customerDAO; // scans all components that implements this interface and picks the first
@Override
@Transactional // Automatically starts and commits transactions)
public List<Customer> getCustomers() {
return customerDAO.getCustomers();
}
@Override
@Transactional
public void saveCustomer(Customer customer) {
customerDAO.saveCustomer(customer);
}
}
Repository
Data Access Object
(DAO) is a design pattern responsible for interfacing
with the database
- It's a
helper
class to talk to the database
- DAO classes are annotated with
@Repository
public interface CustomerDAO {
public List<Customer> getCustomers();
}
@Repository
public class CustomerDAOImpl implements CustomerDAO {
@Autowired // inject dependency
private SessionFactory sessionFactory;
@Override
@Transactional // Automatically starts and commits transactions
public List<Customer> getCustomers() {
Session session = sessionFactory.getCurrentSession();
Query<Customer> query = session.createQuery("from Customer", Customer.class);
List<Customer> customers = query.getResultList();
return customers;
}
}