[java] Vaadin과 데이터베이스 연동하기

Vaadin은 자바 기반의 웹 애플리케이션 개발 프레임워크로서, 데이터베이스와의 연동이 필요한 경우가 많습니다. 이번 글에서는 Vaadin에서 데이터베이스를 연동하는 방법을 알아보겠습니다.

1. 데이터베이스 설정

Vaadin에서 데이터베이스를 연동하기 위해서는 해당 데이터베이스에 접속할 수 있는 JDBC 드라이버가 필요합니다. 먼저, 프로젝트의 dependencies에 해당 드라이버를 추가해야 합니다. 예를 들어, MySQL 데이터베이스를 사용한다면 다음과 같이 Maven을 통해 의존성을 추가할 수 있습니다.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

데이터베이스에 연결하기 위해 필요한 정보(주소, 사용자 이름, 비밀번호)를 이용해 DataSource 객체를 생성합니다. 이는 데이터베이스 연결, 커넥션 풀 관리 등을 담당하게 됩니다.

import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool;
import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool;

// ...

String connectionString = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";

DataSource dataSource = new SimpleJDBCConnectionPool(
        "com.mysql.cj.jdbc.Driver", connectionString, username, password);

2. 데이터베이스와의 상호작용

Vaadin에서 데이터베이스와의 상호작용은 주로 데이터를 읽고 쓰는 작업을 포함합니다. 예를 들어, 데이터베이스에서 데이터를 조회하여 Vaadin의 테이블이나 폼에 표시하거나, 사용자 입력을 받아 데이터를 데이터베이스에 저장하는 작업 등이 있습니다.

데이터를 조회하기 위해서는 SQLContainer를 사용할 수 있습니다. 다음은 데이터베이스의 employees 테이블을 조회하여 Vaadin의 테이블에 표시하는 예제입니다.

import com.vaadin.data.util.sqlcontainer.SQLContainer;
import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool;

// ...

SQLContainer container = new SQLContainer(new TableQuery("employees", dataSource));
Table table = new Table("Employee List", container);

데이터를 쓰기 위해서는 SQLContainer.Item을 사용할 수 있습니다. 다음은 입력 폼을 통해 사용자가 입력한 데이터를 데이터베이스에 저장하는 예제입니다.

import com.vaadin.data.util.sqlcontainer.SQLContainer;
import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool;

// ...

SQLContainer container = new SQLContainer(new TableQuery("employees", dataSource));
Form form = new Form(container);
Button saveButton = new Button("Save", event -> {
    SQLContainer.Item item = container.getItem(container.addItem());
    item.getItemProperty("name").setValue(form.getField("name").getValue());
    item.getItemProperty("age").setValue(form.getField("age").getValue());
    container.commit();
});

마무리

이번 글에서는 Vaadin과 데이터베이스를 연동하는 방법을 간단히 알아보았습니다. 데이터베이스에 접속하고 데이터를 조회하고 쓰는 과정을 기반으로 개발자가 원하는 로직을 작성할 수 있습니다. Vaadin이 제공하는 도구들을 활용하여 보다 쉽게 데이터베이스와의 상호작용을 구현할 수 있습니다.

참고 자료