I am working on a stand-alone Java project (not Java EE), I am currently learning JDBC, I am creating a database where it contains Employee information, such as Personal information, Contact Information, Employee Information and Tax information, all of these are classes with references with each other and they have setters and getters, I am wondering how would I insert their data value in the database/tables I created in the database? in short I have Employee an employee object with like this
Employee(PersonalInformation information,ContactInformation cInformation)
Something like that, how would I add their data in the tables I made in the database?
By using JDBC to send INSERT statements to the database, one for each object in your object graph (assuming you have one table per class).
And yes, that’s a lot of boring, repetitive code to write, which is likely to contain errors and quite a burden to maintain.
Which is why people have written Object-Relational mappers like Hibernate, and there’s a Java standard for that called JPA. Which is part of Java EE, but that doesn’t mean you have to run a Java EE server to use it.
Update: OK, so you cannot use an ORM, probably because you’re supposed to understand how JDBC works first, which makes sense because ORMs are based on JDBC and sometimes you have to go down to that level when there is a problem.
When using JDBC directly, you typically create a DAO (data ccess object) layer that is responsible for writing and reading objects to/from the database. For dealing with a nested object, one DAO can call the other.
And no, the DAOs are not called in the setters and getters. There called by the part of your application that reacts to user input. E.g. when the user opens the application and the start screen shows a list of employees, you’d call an
EmployeeDAO.findAll()method, and when the user makes changes to an employee and clicks on “save”, you’d call theEmployeeDAO.save()method.