Суть паттерна DAO - выделить код доступа к источнику данных и инкапсулировать его в объекте DAO.
Существует класс, который умеет сохранять своё состояние в таблице:
import java.sql.*;
public class Token {
private int id;
private String name;
public Token(){
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
System.out.println("Не могу найти драйвер");
e.printStackTrace();
}
}
public Token(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void insert(){
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
PreparedStatement command = connection.prepareStatement("insert into token (id, name) values (?, ?)");
command.setInt(1, this.getId());
command.setString(2, this.getName());
command.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void update(){
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
PreparedStatement command = connection.prepareStatement("update token set name=? where id=?");
command.setString(1, this.getName());
command.setInt(2, this.getId());
command.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static Token getById(int id){
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")){
PreparedStatement command = connection.prepareStatement("select * from token where id = ?");
command.setInt(1, id);
Token token = null;
ResultSet resultSet = command.executeQuery();
if (resultSet.next()) {
token = new Token(
resultSet.getInt("id"),
resultSet.getString("name"));
}
return token;
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
}
Пример использования:
public class App {
public static void main( String[] args ) {
Token token2 = new Token(2,"два");
token2.insert();
Token token1 = Token.getById(1);
System.out.println(token1.getName());
token1.setName("только один");
token1.update();
}
}
Применим паттерн DAO - перенесём всю логику работы с базой данных в отдельный класс:
import java.sql.*;
public class TokenDAO {
public TokenDAO() {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
System.out.println("Не могу найти драйвер");
e.printStackTrace();
}
}
public void insert(Token token){
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
PreparedStatement command = connection.prepareStatement("insert into token (id, name) values (?, ?)");
command.setInt(1, token.getId());
command.setString(2, token.getName());
command.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void update(Token token){
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")) {
PreparedStatement command = connection.prepareStatement("update token set name=? where id=?");
command.setString(1, token.getName());
command.setInt(2, token.getId());
command.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public Token getdById(int id){
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sample.db")){
PreparedStatement command = connection.prepareStatement("select * from token where id = ?");
command.setInt(1, id);
Token token = null;
ResultSet resultSet = command.executeQuery();
if (resultSet.next()) {
token = new Token(
resultSet.getInt("id"),
resultSet.getString("name"));
}
return token;
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
}
Сам класс Token теперь выглядит так:
public class Token {
private int id;
private String name;
public Token(){
}
public Token(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Использовать надо так:
public class App {
public static void main( String[] args ) {
TokenDAO tokenDAO = new TokenDAO();
Token token2 = new Token(2,"два");
tokenDAO.insert(token2);
Token token1 = tokenDAO.getById(1);
System.out.println(token1.getName());
token1.setName("только один");
tokenDAO.update(token1);
}
}
Код можно упростить, если использовать Spring.