Skip to content

Commit

Permalink
add query examples
Browse files Browse the repository at this point in the history
  • Loading branch information
mkyong committed Aug 1, 2019
1 parent 73a5956 commit d56d32d
Show file tree
Hide file tree
Showing 6 changed files with 281 additions and 3 deletions.
6 changes: 6 additions & 0 deletions spring-jdbc/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@

<dependencies>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
Expand Down
49 changes: 47 additions & 2 deletions spring-jdbc/src/main/java/com/mkyong/StartApplication.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.mkyong;

import com.mkyong.customer.Customer;
import com.mkyong.customer.CustomerRepository;
import com.mkyong.repository.BookRepository;
import com.mkyong.sp.StoredFunction;
import com.mkyong.sp.StoredProcedure1;
Expand Down Expand Up @@ -33,6 +35,9 @@ public class StartApplication implements CommandLineRunner {
@Qualifier("namedParameterJdbcBookRepository") // Test NamedParameterJdbcTemplate
private BookRepository bookRepository;

@Autowired
CustomerRepository customerRepository;

@Autowired
TestData storeProcedureTest;

Expand Down Expand Up @@ -64,11 +69,51 @@ public void run(String... args) {
//storedProcedure2.start();
//storedFunction.start();

start();
//startCustomerApp();

startBookApp();

}

// Tested with H2 database
void startCustomerApp() {

jdbcTemplate.execute("DROP TABLE customer IF EXISTS");
jdbcTemplate.execute("CREATE TABLE customer(" +
"id SERIAL, name VARCHAR(255), age NUMERIC(2), created_date timestamp)");

List<Customer> list = Arrays.asList(
new Customer("Customer A", 19),
new Customer("Customer B", 20),
new Customer("Customer C", 21),
new Customer("Customer D", 22)
);

list.forEach(x -> {
log.info("Saving...{}", x.getName());
customerRepository.save(x);
});

log.info("[FIND_BY_ID]");
log.info("{}", customerRepository.findByCustomerId(1L));
log.info("{}", customerRepository.findByCustomerId2(2L));
log.info("{}", customerRepository.findByCustomerId3(3L));

log.info("[FIND_ALL]");
log.info("{}", customerRepository.findAll());
log.info("{}", customerRepository.findAll2());
log.info("{}", customerRepository.findAll3());
log.info("{}", customerRepository.findAll4());

log.info("[FIND_NAME_BY_ID]");
log.info("{}", customerRepository.findCustomerNameById(4L));

log.info("[COUNT]");
log.info("{}", customerRepository.count());

}

void start() {
void startBookApp() {

log.info("Creating tables for testing...");

Expand Down
68 changes: 68 additions & 0 deletions spring-jdbc/src/main/java/com/mkyong/customer/Customer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package com.mkyong.customer;

import java.time.LocalDateTime;

public class Customer {

private Long ID;
private String name;
private Integer age;
private LocalDateTime createdDate;

public Customer() {
}

public Customer(String name, Integer age) {
this.name = name;
this.age = age;
}

public Customer(Long ID, String name, Integer age, LocalDateTime createdDate) {
this.ID = ID;
this.name = name;
this.age = age;
this.createdDate = createdDate;
}

@Override
public String toString() {
return "Customer{" +
"ID=" + ID +
", name='" + name + '\'' +
", age=" + age +
", createdDate=" + createdDate +
'}';
}

public Long getID() {
return ID;
}

public void setID(Long ID) {
this.ID = ID;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public LocalDateTime getCreatedDate() {
return createdDate;
}

public void setCreatedDate(LocalDateTime createdDate) {
this.createdDate = createdDate;
}
}
138 changes: 138 additions & 0 deletions spring-jdbc/src/main/java/com/mkyong/customer/CustomerRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package com.mkyong.customer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Repository
public class CustomerRepository {

@Autowired
private JdbcTemplate jdbcTemplate;

public int save(Customer customer) {
return jdbcTemplate.update(
"insert into customer (name, age, created_date) values(?,?,?)",
customer.getName(), customer.getAge(), LocalDateTime.now());
}

public Customer findByCustomerId(Long id) {

String sql = "SELECT * FROM CUSTOMER WHERE ID = ?";

return jdbcTemplate.queryForObject(sql, new Object[]{id}, new CustomerRowMapper());

}

public Customer findByCustomerId2(Long id) {

String sql = "SELECT * FROM CUSTOMER WHERE ID = ?";

return (Customer) jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper(Customer.class));

}

public Customer findByCustomerId3(Long id) {

String sql = "SELECT * FROM CUSTOMER WHERE ID = ?";

return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) ->
new Customer(
rs.getLong("id"),
rs.getString("name"),
rs.getInt("age"),
rs.getTimestamp("created_date").toLocalDateTime()
));

}

public List<Customer> findAll() {

String sql = "SELECT * FROM CUSTOMER";

List<Customer> customers = new ArrayList<>();

List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);

for (Map row : rows) {
Customer obj = new Customer();

obj.setID(((Integer) row.get("ID")).longValue());
//obj.setID(((Long) row.get("ID"))); no, ClassCastException
obj.setName((String) row.get("NAME"));
obj.setAge(((BigDecimal) row.get("AGE")).intValue()); // Spring returns BigDecimal, need convert
obj.setCreatedDate(((Timestamp) row.get("CREATED_DATE")).toLocalDateTime());
customers.add(obj);
}

return customers;
}

public List<Customer> findAll2() {

String sql = "SELECT * FROM CUSTOMER";

List<Customer> customers = jdbcTemplate.query(
sql,
new CustomerRowMapper());

return customers;
}

public List<Customer> findAll3() {

String sql = "SELECT * FROM CUSTOMER";

List<Customer> customers = jdbcTemplate.query(
sql,
new BeanPropertyRowMapper(Customer.class));

return customers;
}

public List<Customer> findAll4() {

String sql = "SELECT * FROM CUSTOMER";

return jdbcTemplate.query(
sql,
(rs, rowNum) ->
new Customer(
rs.getLong("id"),
rs.getString("name"),
rs.getInt("age"),
rs.getTimestamp("created_date").toLocalDateTime()
)
);
}

public String findCustomerNameById(Long id) {

String sql = "SELECT NAME FROM CUSTOMER WHERE ID = ?";

return jdbcTemplate.queryForObject(
sql, new Object[]{id}, String.class);

}

public int count() {

String sql = "SELECT COUNT(*) FROM CUSTOMER";

// queryForInt() is Deprecated
// https://www.mkyong.com/spring/jdbctemplate-queryforint-is-deprecated/
//int total = jdbcTemplate.queryForInt(sql);

return jdbcTemplate.queryForObject(sql, Integer.class);

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.mkyong.customer;

import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

public class CustomerRowMapper implements RowMapper<Customer> {

@Override
public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {

Customer customer = new Customer();
customer.setID(rs.getLong("ID"));
customer.setName(rs.getString("NAME"));
customer.setAge(rs.getInt("AGE"));
customer.setCreatedDate(rs.getTimestamp("created_date").toLocalDateTime());

return customer;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.mkyong.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
Expand Down

0 comments on commit d56d32d

Please sign in to comment.