├── .classpath ├── .gitignore ├── .project ├── .settings └── org.eclipse.jdt.core.prefs ├── README.md ├── db.properties └── src ├── application └── App.java ├── db ├── DB.java ├── DbException.java └── DbIntegrityException.java └── model ├── dao ├── DaoFactory.java ├── DepartmentDao.java ├── SellerDao.java └── impl │ └── SellerDaoJDBC.java └── entities ├── Department.java └── Seller.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /bin/ 3 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Java-DAO-JDBC 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=11 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=11 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning 13 | org.eclipse.jdt.core.compiler.release=enabled 14 | org.eclipse.jdt.core.compiler.source=11 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Project DAO(Data Access Object) with JDBC in Java using MySQL 2 | 3 | This project is an implementation of the DAO (Data Access Object) pattern in Java, using JDBC (Java Database Connectivity) to interact with a MySQL database. The DAO pattern is an approach to organize the persistence layer in an application, separating data access operations from business logic. 4 | 5 | ## About the Project 6 | 7 | The project consists of a simple management system for sellers and departments. It allows performing basic CRUD (Create, Read, Update, Delete) operations for sellers and departments, storing the data in a MySQL database. 8 | 9 | ## Features 10 | 11 | The project offers the following features: 12 | 13 | - Query seller by ID. 14 | - Query all sellers. 15 | - Query sellers by department. 16 | - Insert new seller. 17 | - Update seller data. 18 | - Delete a seller. 19 | 20 | ## Project Structure 21 | 22 | The project is organized into packages, with the following structure: 23 | 24 | - `src`: Contains the packages and classes of the project. 25 | - `model.entities`: Contains the entity classes of the system. 26 | - `Department`: Represents the Department entity. 27 | - `Seller`: Represents the Seller entity. 28 | - `model.dao`: Contains the interfaces for the DAO classes. 29 | - `DepartmentDao`: Interface for the Department DAO. 30 | - `SellerDao`: Interface for the Seller DAO. 31 | - `model.dao.impl`: Contains the implementations of the DAO interfaces. 32 | - `DepartmentDaoJDBC`: Implementation of the Department DAO using JDBC. 33 | - `SellerDaoJDBC`: Implementation of the Seller DAO using JDBC. 34 | - `db`: Contains the classes related to the database connection. 35 | - `DB`: Utility class for configuring the database connection. 36 | - `DbException`: Custom exception for handling database errors. 37 | - `DaoFactory`: Class for instantiating DAOs. 38 | - `db.properties`: Configuration file with the database access information. 39 | - `Demo.java`: Demonstration class with examples of using the functionalities. 40 | 41 | ## How to Use the Project 42 | 43 | 1. Clone the project repository to your local environment. 44 | 2. Configure the `db.properties` file with the access information to your MySQL database. 45 | 3. Import the project into your preferred Java IDE (such as Eclipse or IntelliJ). 46 | 4. Ensure that the dependencies are correctly configured (e.g., MySQLConnector). 47 | 48 | ## Class Diagram 49 | 50 | 51 | 52 | ![](https://github.com/jbrun0r/assets/blob/main/Java-DAO-JDBC/class-diagram.png?raw=true) 53 | 54 | ## Overview of the DAO Pattern 55 | 56 | 57 | 58 | ![](https://github.com/jbrun0r/assets/blob/main/Java-DAO-JDBC/data-access-object.png?raw=true) 59 | 60 | ## Overview of JDBC 61 | 62 | 63 | 64 | ![](https://github.com/jbrun0r/assets/blob/main/Java-DAO-JDBC/java-database-connectivity.png?raw=true) 65 | 66 | ## References 67 | 68 | - [DevMedia - DAO Pattern: Data Persistence Using the DAO Pattern](https://www.devmedia.com.br/dao-pattern-persistencia-de-dados-utilizando-o-padrao-dao/30999) 69 | - [Oracle - Java Data Access Object](https://www.oracle.com/technetwork/java/dataaccessobject-138824.html) 70 | -------------------------------------------------------------------------------- /db.properties: -------------------------------------------------------------------------------- 1 | user=root 2 | password=****** 3 | dburl=jdbc:mysql://localhost:3306/jdbc 4 | useSSL=false 5 | -------------------------------------------------------------------------------- /src/application/App.java: -------------------------------------------------------------------------------- 1 | package application; 2 | 3 | import java.util.Date; 4 | import java.util.List; 5 | 6 | import model.dao.DaoFactory; 7 | import model.dao.SellerDao; 8 | import model.entities.Department; 9 | import model.entities.Seller; 10 | 11 | public class App { 12 | 13 | public static void main(String[] args) { 14 | 15 | SellerDao sellerDao = DaoFactory.createSellerDao(); 16 | 17 | Seller seller = sellerDao.findById(3); 18 | System.out.println("Find by id: " + seller); 19 | 20 | Department department = new Department(3, null); 21 | List sellers = sellerDao.findByDepartment(department); 22 | System.out.println("\r\nFind by Department:"); 23 | for (Seller sellerByDep : sellers) { 24 | System.out.println(sellerByDep); 25 | } 26 | 27 | sellers = sellerDao.findAll(); 28 | System.out.println("\r\nFind all:"); 29 | for (Seller sellerByDep : sellers) { 30 | System.out.println(sellerByDep); 31 | } 32 | 33 | Seller newSeller = new Seller(null, "Greg", "greg@gmail.com", new Date(), 4000.0, department); 34 | sellerDao.insert(newSeller); 35 | System.out.println("\r\nNew seller, id: " + newSeller.getId()); 36 | 37 | seller = sellerDao.findById(1); 38 | seller.setName("João"); 39 | sellerDao.update(seller); 40 | System.out.println("\r\nUpdate seller, id: " + seller); 41 | 42 | Integer id = 2; 43 | System.out.println("\r\nDelete seller, id: "+id); 44 | sellerDao.deleteById(id); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/db/DB.java: -------------------------------------------------------------------------------- 1 | package db; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.sql.Connection; 6 | import java.sql.DriverManager; 7 | import java.sql.ResultSet; 8 | import java.sql.SQLException; 9 | import java.sql.Statement; 10 | import java.util.Properties; 11 | 12 | public class DB { 13 | 14 | private static Connection conn = null; 15 | 16 | public static Connection getConnection() { 17 | if (conn == null) { 18 | try { 19 | Properties props = loadProperties(); 20 | String url = props.getProperty("dburl"); 21 | conn = DriverManager.getConnection(url, props); 22 | } catch (SQLException e) { 23 | throw new DbException(e.getMessage()); 24 | } 25 | 26 | } 27 | return conn; 28 | } 29 | 30 | public static void closeConnection() { 31 | if (conn != null) { 32 | try { 33 | conn.close(); 34 | } catch (SQLException e) { 35 | throw new DbException(e.getMessage()); 36 | } 37 | 38 | } 39 | } 40 | 41 | private static Properties loadProperties() { 42 | try (FileInputStream fs = new FileInputStream("db.properties")) { 43 | Properties props = new Properties(); 44 | props.load(fs); 45 | return props; 46 | } catch (IOException e) { 47 | throw new DbException(e.getMessage()); 48 | } 49 | } 50 | 51 | public static void closeStatement(Statement st) { 52 | if(st!=null) { 53 | try { 54 | st.close(); 55 | } catch (SQLException e) { 56 | throw new DbException(e.getMessage()); 57 | } 58 | } 59 | } 60 | 61 | public static void closeResultSet(ResultSet rs) { 62 | if(rs!=null) { 63 | try { 64 | rs.close(); 65 | } catch (SQLException e) { 66 | throw new DbException(e.getMessage()); 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/db/DbException.java: -------------------------------------------------------------------------------- 1 | package db; 2 | 3 | public class DbException extends RuntimeException{ 4 | private static final long serialVersionUID = 1L; 5 | 6 | public DbException(String msg) { 7 | super(msg); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/db/DbIntegrityException.java: -------------------------------------------------------------------------------- 1 | package db; 2 | 3 | public class DbIntegrityException extends RuntimeException { 4 | private static final long serialVersionUID = 1L; 5 | 6 | public DbIntegrityException(String msg) { 7 | super(msg); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/model/dao/DaoFactory.java: -------------------------------------------------------------------------------- 1 | package model.dao; 2 | 3 | import db.DB; 4 | import model.dao.impl.SellerDaoJDBC; 5 | 6 | public class DaoFactory { 7 | 8 | public static SellerDao createSellerDao() { 9 | return new SellerDaoJDBC(DB.getConnection()); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/model/dao/DepartmentDao.java: -------------------------------------------------------------------------------- 1 | package model.dao; 2 | 3 | import java.util.List; 4 | 5 | import model.entities.Department; 6 | 7 | public interface DepartmentDao { 8 | 9 | void insert(Department department); 10 | 11 | void update(Department department); 12 | 13 | void deleteById(Integer id); 14 | 15 | Department findById(Integer id); 16 | 17 | List findAll(); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/model/dao/SellerDao.java: -------------------------------------------------------------------------------- 1 | package model.dao; 2 | 3 | import java.util.List; 4 | 5 | import model.entities.Department; 6 | import model.entities.Seller; 7 | 8 | public interface SellerDao { 9 | 10 | void insert(Seller seller); 11 | 12 | void update(Seller seller); 13 | 14 | void deleteById(Integer id); 15 | 16 | Seller findById(Integer id); 17 | 18 | List findAll(); 19 | List findByDepartment(Department department); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/model/dao/impl/SellerDaoJDBC.java: -------------------------------------------------------------------------------- 1 | package model.dao.impl; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.sql.Statement; 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.List; 11 | import java.util.Map; 12 | 13 | import db.DB; 14 | import db.DbException; 15 | import model.dao.SellerDao; 16 | import model.entities.Department; 17 | import model.entities.Seller; 18 | 19 | public class SellerDaoJDBC implements SellerDao{ 20 | 21 | private Connection connection; 22 | 23 | public SellerDaoJDBC(Connection connection) { 24 | this.connection = connection; 25 | } 26 | 27 | @Override 28 | public void insert(Seller seller) { 29 | PreparedStatement statement = null; 30 | 31 | try { 32 | statement = connection.prepareStatement( 33 | "INSERT INTO seller " 34 | + "(Name, Email, BirthDate, BaseSalary, DepartmentId) " 35 | + "VALUES (?, ?, ?, ?, ?)", 36 | Statement.RETURN_GENERATED_KEYS); 37 | 38 | statement.setString(1, seller.getName()); 39 | statement.setString(2, seller.getEmail()); 40 | statement.setDate(3, new java.sql.Date(seller.getBirthDate().getTime())); 41 | statement.setDouble(4, seller.getBaseSalary()); 42 | statement.setInt(5, seller.getDepartment().getId()); 43 | 44 | int rowsAffedcted = statement.executeUpdate(); 45 | 46 | if(rowsAffedcted>0) { 47 | ResultSet result = statement.getGeneratedKeys(); 48 | if(result.next()) { 49 | int id = result.getInt(1); 50 | seller.setId(id); 51 | } 52 | DB.closeResultSet(result); 53 | } 54 | else { 55 | throw new DbException("No rows affected!"); 56 | } 57 | } 58 | catch(SQLException e) { 59 | throw new DbException(e.getMessage()); 60 | } 61 | finally { 62 | DB.closeStatement(statement); 63 | } 64 | 65 | } 66 | 67 | @Override 68 | public void update(Seller seller) { 69 | PreparedStatement statement = null; 70 | 71 | try { 72 | statement = connection.prepareStatement( 73 | "UPDATE seller " 74 | + "SET Name = ?, Email = ?, BirthDate = ?, BaseSalary = ?, DepartmentId = ? " 75 | + "WHERE Id = ?"); 76 | 77 | statement.setString(1, seller.getName()); 78 | statement.setString(2, seller.getEmail()); 79 | statement.setDate(3, new java.sql.Date(seller.getBirthDate().getTime())); 80 | statement.setDouble(4, seller.getBaseSalary()); 81 | statement.setInt(5, seller.getDepartment().getId()); 82 | statement.setInt(6, seller.getId()); 83 | 84 | statement.executeUpdate(); 85 | 86 | } 87 | catch(SQLException e) { 88 | throw new DbException(e.getMessage()); 89 | } 90 | finally { 91 | DB.closeStatement(statement); 92 | } 93 | 94 | } 95 | 96 | @Override 97 | public void deleteById(Integer id) { 98 | PreparedStatement statement = null; 99 | 100 | try { 101 | statement = connection.prepareStatement("DELETE FROM seller WHERE Id = ?"); 102 | statement.setInt(1, id); 103 | 104 | statement.executeUpdate(); 105 | } 106 | catch(SQLException e){ 107 | throw new DbException(e.getMessage()); 108 | } 109 | finally { 110 | DB.closeStatement(statement); 111 | } 112 | } 113 | 114 | @Override 115 | public Seller findById(Integer id) { 116 | PreparedStatement statement = null; 117 | ResultSet result = null; 118 | 119 | String baseQuery = "SELECT seller.*, department.Name AS DepName " 120 | + "FROM seller INNER JOIN department " 121 | + "ON seller.DepartmentId = department.Id " 122 | + "WHERE seller.Id = ?"; 123 | 124 | try { 125 | statement = connection.prepareStatement(baseQuery); 126 | statement.setInt(1, id); 127 | result = statement.executeQuery(); 128 | 129 | if (result.next()) { 130 | Department department = instantiateDepartment(result); 131 | Seller seller = instantiateSeller(result, department); 132 | return seller; 133 | } 134 | 135 | return null; 136 | } 137 | catch(SQLException e) { 138 | throw new DbException(e.getMessage()); 139 | } 140 | finally { 141 | DB.closeStatement(statement); 142 | DB.closeResultSet(result); 143 | } 144 | } 145 | 146 | 147 | @Override 148 | public List findAll() { 149 | PreparedStatement statement = null; 150 | ResultSet result = null; 151 | 152 | try { 153 | statement = connection.prepareStatement( 154 | "SELECT seller.*, department.Name as DepName " 155 | + "FROM seller INNER JOIN department " 156 | + "ON seller.DepartmentId = department.Id " 157 | + "ORDER BY Name"); 158 | 159 | result = statement.executeQuery(); 160 | 161 | List sellers = new ArrayList<>(); 162 | Map map = new HashMap<>(); 163 | 164 | while (result.next()) { 165 | 166 | Department dep = map.get(result.getInt("DepartmentId")); 167 | 168 | if(dep == null) { 169 | dep = instantiateDepartment(result); 170 | map.put(result.getInt("DepartmentId"), dep); 171 | } 172 | 173 | Seller seller = instantiateSeller(result, dep); 174 | sellers.add(seller); 175 | } 176 | return sellers; 177 | } 178 | catch(SQLException e) { 179 | throw new DbException(e.getMessage()); 180 | } 181 | finally { 182 | DB.closeStatement(statement); 183 | DB.closeResultSet(result); 184 | } 185 | } 186 | 187 | @Override 188 | public List findByDepartment(Department department) { 189 | PreparedStatement statement = null; 190 | ResultSet result = null; 191 | 192 | try { 193 | statement = connection.prepareStatement( 194 | "SELECT seller.*, department.Name as DepName " 195 | + "FROM seller INNER JOIN department " 196 | + "ON seller.DepartmentId = department.Id " 197 | + "WHERE DepartmentId = ? " 198 | + "ORDER BY Name"); 199 | 200 | statement.setInt(1, department.getId()); 201 | result = statement.executeQuery(); 202 | 203 | List sellers = new ArrayList<>(); 204 | Map map = new HashMap<>(); 205 | 206 | while (result.next()) { 207 | 208 | Department dep = map.get(result.getInt("DepartmentId")); 209 | 210 | if(dep == null) { 211 | dep = instantiateDepartment(result); 212 | map.put(result.getInt("DepartmentId"), dep); 213 | } 214 | 215 | Seller seller = instantiateSeller(result, dep); 216 | sellers.add(seller); 217 | } 218 | return sellers; 219 | } 220 | catch(SQLException e) { 221 | throw new DbException(e.getMessage()); 222 | } 223 | finally { 224 | DB.closeStatement(statement); 225 | DB.closeResultSet(result); 226 | } 227 | } 228 | 229 | private Department instantiateDepartment(ResultSet result) throws SQLException { 230 | Department department = new Department(); 231 | department.setId(result.getInt("DepartmentId")); 232 | department.setName(result.getString("DepName")); 233 | return department; 234 | } 235 | 236 | private Seller instantiateSeller(ResultSet result, Department department) throws SQLException { 237 | Seller seller = new Seller(); 238 | seller.setId(result.getInt("Id")); 239 | seller.setName(result.getString("Name")); 240 | seller.setEmail(result.getString("Email")); 241 | seller.setBaseSalary(result.getDouble("BaseSalary")); 242 | seller.setBirthDate(result.getDate("BirthDate")); 243 | seller.setDepartment(department); 244 | return seller; 245 | } 246 | 247 | } 248 | -------------------------------------------------------------------------------- /src/model/entities/Department.java: -------------------------------------------------------------------------------- 1 | package model.entities; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Department implements Serializable { 6 | 7 | private static final long serialVersionUID = 1L; 8 | 9 | private Integer id; 10 | private String name; 11 | 12 | public Department() { 13 | } 14 | 15 | public Department(Integer id, String name) { 16 | this.id = id; 17 | this.name = name; 18 | } 19 | 20 | public Integer getId() { 21 | return id; 22 | } 23 | 24 | public void setId(Integer id) { 25 | this.id = id; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public void setName(String name) { 33 | this.name = name; 34 | } 35 | 36 | @Override 37 | public int hashCode() { 38 | final int prime = 31; 39 | int result = 1; 40 | result = prime * result + ((id == null) ? 0 : id.hashCode()); 41 | return result; 42 | } 43 | 44 | @Override 45 | public boolean equals(Object obj) { 46 | if (this == obj) 47 | return true; 48 | if (obj == null) 49 | return false; 50 | if (getClass() != obj.getClass()) 51 | return false; 52 | Department other = (Department) obj; 53 | if (id == null) { 54 | if (other.id != null) 55 | return false; 56 | } else if (!id.equals(other.id)) 57 | return false; 58 | return true; 59 | } 60 | 61 | @Override 62 | public String toString() { 63 | return "Department [id=" + id + ", name=" + name + "]"; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/model/entities/Seller.java: -------------------------------------------------------------------------------- 1 | package model.entities; 2 | 3 | import java.io.Serializable; 4 | import java.util.Date; 5 | 6 | public class Seller implements Serializable { 7 | 8 | private static final long serialVersionUID = 1L; 9 | 10 | private Integer id; 11 | private String name; 12 | private String email; 13 | private Date birthDate; 14 | private Double baseSalary; 15 | 16 | private Department department; 17 | 18 | public Seller() { 19 | } 20 | 21 | public Seller(Integer id, String name, String email, Date birthDate, Double baseSalary, Department department) { 22 | this.id = id; 23 | this.name = name; 24 | this.email = email; 25 | this.birthDate = birthDate; 26 | this.baseSalary = baseSalary; 27 | this.department = department; 28 | } 29 | 30 | public Integer getId() { 31 | return id; 32 | } 33 | 34 | public void setId(Integer id) { 35 | this.id = id; 36 | } 37 | 38 | public String getName() { 39 | return name; 40 | } 41 | 42 | public void setName(String name) { 43 | this.name = name; 44 | } 45 | 46 | public String getEmail() { 47 | return email; 48 | } 49 | 50 | public void setEmail(String email) { 51 | this.email = email; 52 | } 53 | 54 | public Date getBirthDate() { 55 | return birthDate; 56 | } 57 | 58 | public void setBirthDate(Date birthDate) { 59 | this.birthDate = birthDate; 60 | } 61 | 62 | public Double getBaseSalary() { 63 | return baseSalary; 64 | } 65 | 66 | public void setBaseSalary(Double baseSalary) { 67 | this.baseSalary = baseSalary; 68 | } 69 | 70 | public Department getDepartment() { 71 | return department; 72 | } 73 | 74 | public void setDepartment(Department department) { 75 | this.department = department; 76 | } 77 | 78 | @Override 79 | public int hashCode() { 80 | final int prime = 31; 81 | int result = 1; 82 | result = prime * result + ((id == null) ? 0 : id.hashCode()); 83 | return result; 84 | } 85 | 86 | @Override 87 | public boolean equals(Object obj) { 88 | if (this == obj) 89 | return true; 90 | if (obj == null) 91 | return false; 92 | if (getClass() != obj.getClass()) 93 | return false; 94 | Seller other = (Seller) obj; 95 | if (id == null) { 96 | if (other.id != null) 97 | return false; 98 | } else if (!id.equals(other.id)) 99 | return false; 100 | return true; 101 | } 102 | 103 | @Override 104 | public String toString() { 105 | return "Seller [id=" + id + ", name=" + name + ", email=" + email + ", birthDate=" + birthDate + ", baseSalary=" 106 | + baseSalary + ", department=" + department + "]"; 107 | } 108 | 109 | } 110 | --------------------------------------------------------------------------------