16 - Spring JDBC - Exercise
Task
Create a new project using Spring Initializr https://start.spring.io/ . In the dependencies section on the right hand side select
JDBC API
andMySQL Driver
. Name your projectSpringDB
.Download your project and unzip it into your
IdeaProjects
folder. Open the project in your IntelliJ. RunMaven install
if necessary.Open
application.properties
and type in your database address and credentials (make sure you provide the correct password for your database!)spring.datasource.url=jdbc:mysql://127.0.0.1:3306/employee_sys spring.datasource.username=root spring.datasource.password= spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
Create a java class that will match one of your tables. For example, for this SQL table we would create a class called
Department
with three private attributes -int dep_id
,String dep_name
andint team_id
. Provide setters for all three attributes and generatetoString
method.Create a new class called
DepartmentRepository
. Annotate it with@Repository
. Inside the class, autowire a variable of typeJdbcTemplate
.@Autowired JdbcTemplate jdbcTemplate;
Create an inner class
DepartmentRowMapper
that implements theRowMapper<Department>
interface. It needs to provide one methodmapRow
that takes two parameters - one of typeResultSet
, oneint
for row number. It can throwSQLException
. Within the body of the method provide the mapping between a row in the table and an object of typeDepartment
.private class DepartmentRowMapper implements RowMapper<Department> { public Department mapRow(ResultSet rs, int rowNum) throws SQLException{ Department dept = new Department(); dept.setDep_id(rs.getInt("dep_id")); dept.setDep_name(rs.getString("dep_name")); dept.setTeam_id(rs.getInt("team_id")); return dept; } }
Within the body of the
DepartmentRepository
, create a public method that will return a list ofDepartment
type objects. The method does not need parameters. Inside the body of the method, use thejdbcTemplate
'squery
method, pass in your SQL query and an instance of theDepartmentRowMapper
class. Return the list of departments.Make your
SpringDBApplication
class implement theCommandLineRunner
interface. Provide therun
method.Autowire your
DepartmentRepository
class into theSpringDBApplication
. Within therun
method, invoke thefindAllDepartments()
method created on the repository and print out all the departments.