import java.util.Date;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
class Main {
public static void main(String args[]) throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class);
DataSource dataSource = (DataSource) ac.getBean("dataSource");
// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
Customer customer = new Customer();
customer.setId(3L);
customer.setFirstName("FN");
customer.setLastName("LN");
customer.setLastLogin(new Date());
customer.setComments("CLOB string");
long id = new SimpleJdbcInsert(dataSource).
withTableName("customer").
usingColumns("first_name", "last_name", "last_login", "comments").
usingGeneratedKeyColumns("id").
executeAndReturnKey(new BeanPropertySqlParameterSource(customer)).longValue();
System.out.println(id);
}
}
class Customer {
private Long id;
private String firstName;
private String lastName;
private Date lastLogin;
private String comments;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getLastLogin() {
return lastLogin;
}
public void setLastLogin(Date lastLogin) {
this.lastLogin = lastLogin;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Customer");
sb.append("{id=").append(id);
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", lastLogin=").append(lastLogin);
sb.append(", comments='").append(comments).append('\'');
sb.append('}');
return sb.toString();
}
}
|