The following example show you how to use the Spring’s JdbcTemplate
class to insert a record into database.
package org.kodejava.spring.jdbc;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.sql.Types;
import java.util.Date;
public class InsertDemo {
private static final String INSERT_QUERY =
"INSERT INTO record (title, " +
" release_date, " +
" artist_id, " +
" label_id, " +
" created) " +
"VALUES (?, ?, ?, ?, ?)";
private final DataSource dataSource;
public InsertDemo(DataSource dataSource) {
this.dataSource = dataSource;
}
public static DriverManagerDataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:mysql://localhost/musicdb");
dataSource.setUsername("root");
dataSource.setPassword("");
return dataSource;
}
public static void main(String[] args) {
InsertDemo demo = new InsertDemo(getDataSource());
demo.saveRecord("Rock Beatles", new Date(), 1, 1);
}
public void saveRecord(String title, Date releaseDate,
Integer artistId, Integer labelId) {
// Creates an instance of JdbcTemplate and passes a connection
// to the database.
JdbcTemplate template = new JdbcTemplate(this.dataSource);
// Defines the query arguments and the corresponding SQL types
// of the arguments.
Object[] params = new Object[]{
title, releaseDate, artistId, labelId, new Date()
};
int[] types = new int[]{
Types.VARCHAR,
Types.DATE,
Types.INTEGER,
Types.INTEGER,
Types.DATE
};
// Calls JdbcTemplate.update() methods to create a new data
// in the records table. The update method in general will
// return number of row / rows processed by the executed query
int row = template.update(INSERT_QUERY, params, types);
System.out.println(row + " row inserted.");
}
}
Maven Dependencies
<dependencies>
<!-- https://search.maven.org/remotecontent?filepath=org/springframework/spring-jdbc/5.3.21/spring-jdbc-5.3.21.jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.21</version>
</dependency>
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.29/mysql-connector-java-8.0.29.jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
How can we get the primary key value after executing insert this way.
Hi Anant,
Using Spring JDBCTemplate you can do it in the following way to get the generated key.