Data
Persist data without turning the controller into a data layer.
Data Access
So far, the application's data has lived in in-memory lists. That was enough to understand routing and form binding, and it is untenable beyond that: everything disappears on restart, nothing is shared between two instances, and no even slightly refined query can be expressed.
Moving to a relational database is the point where many Spring MVC applications degrade. The controller, until now lean, starts opening connections, writing SQL, and managing transactions. You find try/catch/finally blocks around JDBC resources, ResultSet-to-object mapping code, and error handling that varies from one method to the next. The controller becomes exactly what Spring MVC was supposed to eliminate: a place where everything gets mixed together.
The problem is not just aesthetic. Mixing data access and the web layer makes transactions uncontrollable. A controller method that writes to three tables with no explicit transaction boundary can leave the database in an intermediate state if the third write fails — and nothing in the code signals that this risk exists.
This lesson sets up the separation that prevents this: an entity describes the table, a repository provides the queries, a service carries the business logic and delimits transactions, and the controller does nothing but translate HTTP. We add pagination, because an unpaginated list is a deferred outage, and we deal with the lazy-loading trap that produces those LazyInitializationException errors in the middle of a page.
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion