JdbcTemplate – podstawy
JdbcTemplate – podstawy
JdbcTemplate to mechanizm który wspiera operacje na bazie danych z użyciem jdbc. Ten artykuł to kilka podstawowych przykładów z użyciem JdbcTemplate. Zaczynamy od projektu Spring Boota – plik pom.xml – niezbędne zależności:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
Klasa modelu:
@ToString @Getter @Setter @AllArgsConstructor public class Person { private long id; private String name; private String surname; public Person() { } }
Klasa startowa:
@SpringBootApplication public class JdbcTemplateApplication implements CommandLineRunner { @Autowired JdbcTemplate jdbcTemplate; public static void main(String[] args) { SpringApplication.run(JdbcTemplateApplication.class, args); } @Override public void run(String... strings) throws Exception { jdbcTemplate.execute("CREATE TABLE persons(" + "id SERIAL, name VARCHAR(255), surname VARCHAR(255))"); List<Object[]> divideNames = Arrays.asList("Alice Spring", "James semaJ", "Alice Jok").stream() .map(name -> name.split(" ")) .collect(Collectors.toList()); divideNames.forEach(item -> System.out.println(item[0] + " " + item[1])); jdbcTemplate.batchUpdate("INSERT INTO persons(name, surname) VALUES (?,?)", divideNames); jdbcTemplate.query( "SELECT id, name, surname FROM persons WHERE name = ?", new Object[] { "Alice" }, (rs, rowNum) -> new Person(rs.getLong("id"), rs.getString("name"), rs.getString("surname")) ).forEach(customer -> System.out.println(customer)); Person alice = jdbcTemplate.queryForObject( "SELECT id, name, surname FROM persons WHERE id = ?", new Object[] { "1" }, (rs, rowNum) -> new Person(rs.getLong("id"), rs.getString("name"), rs.getString("surname")) ); System.out.println(alice); Person james = (Person) jdbcTemplate.queryForObject( "SELECT id, name, surname FROM persons WHERE id = ?", new Object[] { "2" }, new BeanPropertyRowMapper(Person.class)); System.out.println(james); String name = jdbcTemplate.queryForObject( "SELECT name FROM persons WHERE id = ?", new Object[] { "2" }, String.class); System.out.println(name); } }
wynik:
Alice Spring James semaJ Alice Jok Person(id=1, name=Alice, surname=Spring) Person(id=3, name=Alice, surname=Jok) Person(id=1, name=Alice, surname=Spring) Person(id=2, name=James, surname=semaJ) James
Leave a comment