By your design, you should be able just to add appropriate columns to the insert
query, and update parameters:
// EmployeeDAOImpl
private final static String INSERT_EMPLOYEE = "insert into employee (id, name, surname, age, gender, contact, address, city, country) values (?,?,?,?,?,?,?,?,?)";
// ...
@Override
public void saveEmployee(Employee employee) throws SQLException {
try {
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_EMPLOYEE);
preparedStatement.setInt(1, employee.getId());
preparedStatement.setString(2, employee.getName());
preparedStatement.setString(3, employee.getSurname());
preparedStatement.setInt(4, employee.getAge());
preparedStatement.setString(5, employee.getGender());
preparedStatement.setString(6, employee.getContact());
//index 7,8 and 9 are address, city and country...
preparedStatement.setString(7, employee.getAddress().getAddress());
preparedStatement.setString(8, employee.getAddress().getCity());
preparedStatement.setString(9, employee.getAddress().getCountry());
preparedStatement.executeUpdate();
preparedStatement.close();
System.out.println("Employee is inserted..." + employee);
} catch (SQLException e) {
e.printStackTrace();
}
}
And set the fields in MainTest
:
public class MainTest {
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("EmployeeJDBC.xml");
EmployeeDAO dao = context.getBean(EmployeeDAO.class);
Address address = new Address("RandAddress", "RandCity", "RandCountry");
Employee employee = new Employee(1, "John", "Doe", 24, "M", "+15555555555", address);
dao.saveEmployee(employee);
}
}
CLICK HERE to find out more related problems solutions.