Java에서 데이터 액세스 객체 구현

Sarwan Soomro 2024년2월15일
  1. Java의 데이터 액세스 개체 이해
  2. Java에서 MySQL 서버에 연결
  3. Java의 MySQL 데이터베이스에서 데이터 액세스 개체 구현
Java에서 데이터 액세스 객체 구현

새로운 데이터베이스 mydbproducts 테이블을 생성하여 Java에서 DAO를 사용한 데이터 삽입의 실시간 구현을 보여줍니다.

우리의 DAO 모델은 CRUD 애플리케이션을 동적으로 사용할 수 있습니다. 데이터베이스 연결을 위해 mysql-connector-java-8.0.22JDBS 드라이버를 사용합니다.

데이터에 대한 투명한 액세스를 제공하기 위해 개체의 기본 데이터 액세스 구현을 성공적으로 추상화합니다.

Java의 데이터 액세스 개체 이해

이 패턴을 사용하여 DAO와의 인터페이스를 구현합니다. 이 모델은 추상 데이터 소스를 관리할 수 있는 사용자 정의이지만 완전한 기능을 갖춘 Java 데이터 액세스 개체를 대략적으로 표현한 것입니다.

데이터베이스 작업을 변경하려고 한다고 가정합니다. 메인 클래스를 수정하기만 하면 됩니다.

이 경우 우리의 메인 클래스는 JDBC 데모로 정의됩니다.

DAO 패턴:

DAO 모델

우리는 처음부터 당신을 혼동하지 않을 것입니다. 따라서 복사 및 붙여넣기가 아닌 인터페이스를 생성하는 논리를 구축하는 데 필요한 만큼 간단하게 유지합니다.

즉, 이것은 이 예제에서 addProduct인 함수의 개체 인스턴스인 기본 클래스에서 throw된 생성자를 통해 전달된 제품 값을 포함하는 product 클래스입니다.

// Product class
class Product {
  int id;
  String name;
  // add more values
}

그리고 데이터 액세스 개체 패턴을 사용하여 데이터베이스를 관리하는 인터페이스가 있습니다. 당분간은 필수로 둡시다.

데이터베이스 테이블에 제품을 추가할 수 있는 간단한 기능을 확인하십시오.

public static void main(String[] args) {
  // Now let us insert new product
  // constructor PDAO class
  // objects
  ProDAO dao2 = new ProDAO(); // constructor
  Product pro = new Product(); // constructor
  // values to insert
  // dynamically modify values from here later
  pro.id = 3;
  pro.name = "Oppo LOL";
  // we have created a separate function for the db connection
  dao2.Dbconnect();
  // it is set to addProduct as of now, you can run CRUD directly from here
  dao2.addProduct(pro);
}

이것은 구현 코드 섹션에서 실행할 DAO의 일반적인 데모입니다.

MySQL에 데이터베이스를 생성한 다음 MySQL 커넥터 jar 파일을 사용하여 SQL 서버에 연결한다는 점에 유의하십시오.

메모
시스템에서 이 코드를 구현하려면 MySQL 서버가 필요합니다.

걱정 하지마! CLI를 사용하여 데이터베이스를 생성하는 방법도 보여주기 때문입니다.

Windows OS를 사용하는 경우:

새 데이터베이스 및 테이블 생성

메모
이것은 MySQL을 시작하는 완벽한 방법입니다. 구조적 쿼리를 이해해야 하는 대로 이해할 수 있습니다.

그러나 MySQL Workbench, SQL Yog, phpMyAdmin과 같은 GUI를 사용하여 원하는 데이터베이스를 생성할 수 있습니다.

Java에서 MySQL 서버에 연결

관점에서 사물을 유지하고 더러운 코드를 피하기 위해. 우리는 별도의 데이터베이스 기능을 만들 것입니다.

// Database Connection will use jdbc driver from the mysql connector jar
public void Dbconnect() {
  try {
    Class.forName("com.mysql.cj.jdbc.Driver"); // Mysql Connector's JDBC driver is loaded
    // connection to mysql
    con = DriverManager.getConnection(
        "jdbc:mysql://localhost/mydb", "root", ""); // URL, database name after
    // localhost, user name,
    // password
  } catch (Exception ex) {
    System.out.println(ex);
  }
}

MySQL 프로젝트에 이 연결을 사용할 수 있습니다. 그리고 이전 버전의 Java를 사용하는 경우 Class.forName("com.mysql.jdbc.Driver");을 사용하는 것을 잊지 마십시오. JDBC를 로드하기 위해.

Java의 MySQL 데이터베이스에서 데이터 액세스 개체 구현

첫째, 런타임 중에 예외 및 경고를 피하기 위해 경로를 올바르게 작성하는 데 도움이 됩니다.

Java 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 경로를 빌드하고 jar 파일을 구성하면 자주 발생하는 오류를 피할 수 있습니다. 빌드 경로가 아래 이미지와 같은지 확인하십시오.

jar 파일의 빌드 경로 구성

개념이 명확하다면 우리 모델의 다음 DAO 구현을 이해할 수 있을 것입니다. 그럼에도 불구하고 코드의 각 요소에 대해 설명했습니다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

// This Data Access Object DAO is a dynamic way to handle database records.

// main class
class DAOexample {
  public static void main(String[] args) {
    // Now let us insert new product
    // constructor PDAO class
    // objects
    ProDAO dao2 = new ProDAO(); // constructor
    Product pro = new Product(); // constructor
    // values to insert
    // dynamically modify values from here later
    pro.id = 3;
    pro.name = "Oppo LOL";
    // we have created a separate function for the db connection
    dao2.Dbconnect();
    // it is set to addProduct as of now, you can run CRUD directly from here
    dao2.addProduct(pro);
  }
}

class ProDAO {
  Connection con = null;

  // Database Connection will use jdbc driver from the mysql connector jar
  public void Dbconnect() {
    try {
      Class.forName("com.mysql.cj.jdbc.Driver");
      // connection to mysql
      con = DriverManager.getConnection(
          "jdbc:mysql://localhost/mydb", "root", ""); // URL, database name after
      // localhost, user name,
      // password
    } catch (Exception ex) {
      System.out.println(ex);
    }
  }

  // We will use the insert operation in this function, its conductor is already
  // declared in the main class (DAO)
  public void addProduct(Product p) { // this function will insert values
    // insert query
    // using prepared statements
    String query2 = "insert into products values (?,?)";
    try {
      PreparedStatement pst;
      pst = con.prepareStatement(query2);
      pst.setInt(1, p.id);
      pst.setString(2, p.name); //
      pst.executeUpdate(); // executeUpdate is used for the insertion of the data
      System.out.println("Inserted!");
    } catch (Exception ex) {
    }
  }
}

// Product class
class Product {
  int id;
  String name;
  // add more values
}

출력:

데이터 액세스 개체를 사용하여 새 값 삽입

여전히 질문이 있는 경우 jar 파일과 첫 번째 DAO를 구성하는 데 필요한 모든 것이 포함된 이 구현의 전체 zip 폴더를 제공합니다.

Sarwan Soomro avatar Sarwan Soomro avatar

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

LinkedIn

관련 문장 - Java Object