How to Insert record in database using JdbcTemplate and Java 8 ?

To Insert record in database using JdbcTemplate and Java 8 here first we create a Employee table with name and designation column.
In entrySet() we fetch data with getKey() and getValue() form.then java 8 stream method take this value and pass to employee insert query which inside foreach method.
JdbcTemplate class is the core class in the JDBC core package.
Create a new JdbcTemplate object, with the given datasource to obtain connections.

EmployeeDao interface :

				
					import java.util.Map;
public interface EmployeeDao {
	void insertEmployee(Map<String, Object> responseMap);
}
				
			

EmployeeDaoImpl class :-

				
					import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class EmployeeDaoImpl implements EmployeeDao {

	JdbcTemplate template;

	public EmployeeDaoImpl(DataSource ds) {
		template = new JdbcTemplate(ds);
	}

	public void insertEmployee(Map<String, Object> responseMap) {
		long startTime = System.currentTimeMillis();
		try {
			responseMap.entrySet().stream()
					.forEach(e -> template.update("insert into Employee(name,department)" + " values(?,?)",
							new Object[] { e.getKey(), e.getValue() }));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
	}
}
				
			

Leave a Comment

Your email address will not be published. Required fields are marked *