By GokiSoft.com| 20:49 02/02/2023|
Java Advanced

Hướng dẫn phát triển dự án sử dụng mô hình ORM - Java

#pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.gokisoft</groupId>
    <artifactId>C2110L</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>18</maven.compiler.source>
        <maven.compiler.target>18</maven.compiler.target>
        <exec.mainClass>com.gokisoft.C2110L</exec.mainClass>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>
    </dependencies>
</project>

#BaseDAO.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author diepvan
 */
public class BaseDAO {
    static Connection conn = null;
    static PreparedStatement statement = null;

    static void openConnection() {
        try {
            //Mo ket noi
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/C2109I", "root", "");
        } catch (SQLException ex) {
            Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static void closeConnection() {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException ex) {
                Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

#BookDAO.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.dao;

import com.gokisoft.models.Book;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author diepvan
 */
public class BookDAO extends BaseDAO{
    public static List<Book> list() {
        List<Book> dataList = new ArrayList<>();

        openConnection();

        try {
            //Thuc thi lenh
            String sql = "select * from books";
            statement = conn.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                Book book = new Book(
                        resultSet.getInt("id"),
                        resultSet.getString("bookname"),
                        resultSet.getFloat("price"),
                        resultSet.getString("author_name")
                );
                dataList.add(book);
            }
        } catch (SQLException ex) {
            Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        closeConnection();

        return dataList;
    }

    public static void insert(Book book) {
        openConnection();

        String sql = "insert into books(bookname, price, author_name) values (?, ?, ?)";
        try {
            statement = conn.prepareStatement(sql);
            statement.setString(1, book.getBookName());
            statement.setFloat(2, book.getPrice());
            statement.setString(3, book.getAuthorName());

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        closeConnection();
    }

    public static void update(Book book) {
        openConnection();

        String sql = "update books set bookname = ?, price = ?, author_name = ? where id = ?";
        try {
            statement = conn.prepareStatement(sql);
            statement.setString(1, book.getBookName());
            statement.setFloat(2, book.getPrice());
            statement.setString(3, book.getAuthorName());
            statement.setInt(4, book.getId());

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        closeConnection();
    }

    public static void delete(int id) {
        openConnection();

        String sql = "delete from books where id = ?";
        try {
            statement = conn.prepareStatement(sql);
            statement.setInt(1, id);

            statement.execute();
        } catch (SQLException ex) {
            Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        closeConnection();
    }

    public static Book find(int id) {
        Book book = null;
        
        openConnection();

        try {
            //Thuc thi lenh
            String sql = "select * from books where id = ?";
            statement = conn.prepareStatement(sql);
            statement.setInt(1, id);
            
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                book = new Book(
                        resultSet.getInt("id"),
                        resultSet.getString("bookname"),
                        resultSet.getFloat("price"),
                        resultSet.getString("author_name")
                );
                break;
            }
        } catch (SQLException ex) {
            Logger.getLogger(BookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        closeConnection();
        
        return book;
    }
}

#Book.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.models;

/**
 *
 * @author diepvan
 */
public class Book {
    int id;
    String bookName;
    float price;
    String authorName;

    public Book() {
    }

    public Book(int id, String bookName, float price, String authorName) {
        this.id = id;
        this.bookName = bookName;
        this.price = price;
        this.authorName = authorName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getAuthorName() {
        return authorName;
    }

    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    @Override
    public String toString() {
        return "Book{" + "id=" + id + ", bookName=" + bookName + ", price=" + price + ", authorName=" + authorName + '}';
    }
    
    
}

#Users.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.gokisoft.models;

/**
 *
 * @author diepvan
 */
public class Users {
    int id;
    String fullname;
    String email;
    String address;

    public Users() {
    }

    public Users(int id, String fullname, String email, String address) {
        this.id = id;
        this.fullname = fullname;
        this.email = email;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Users{" + "id=" + id + ", fullname=" + fullname + ", email=" + email + ", address=" + address + '}';
    }
    
    
}

#Main.java

/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Project/Maven2/JavaApp/src/main/java/${packagePath}/${mainClassName}.java to edit this template
 */

package com.gokisoft;

import com.gokisoft.dao.BookDAO;
import com.gokisoft.models.Book;
import java.util.List;

/**
 *
 * @author diepvan
 */
public class Main {

    public static void main(String[] args) {
        List<Book> bookList = BookDAO.list();
        
        for (Book book : bookList) {
            System.out.println(book);
        }

//        Book b = new Book(0, "ABC", 2000, "ABC");
//        BookDAO.insert(b);
    }
}



Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)

Đăng nhập để làm bài kiểm tra

Chưa có kết quả nào trước đó