Skip to content

Instantly share code, notes, and snippets.

@jasoet
Created October 6, 2012 08:07
Show Gist options
  • Save jasoet/3844362 to your computer and use it in GitHub Desktop.
Save jasoet/3844362 to your computer and use it in GitHub Desktop.
Sample ProductDAOImpl
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.secondstack.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.secondstack.dao.ProductDAO;
import org.secondstack.model.Category;
import org.secondstack.model.Product;
/**
*
* @author Deny Prasetyo
*/
public class ProductDAOImpl implements ProductDAO {
private Connection connection;
public ProductDAOImpl(Connection connection) {
this.connection = connection;
}
@Override
public int save(Product product) throws SQLException {
String sql = "INSERT INTO product (name,description,price,expireddate,category_id) VALUES (?,?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, product.getName());
statement.setString(2, product.getDescription());
statement.setDouble(3, product.getPrice());
statement.setDate(3, new java.sql.Date(product.getExpiredDate().getTime()));
if (product.getCategory() != null) {
statement.setInt(4, product.getCategory().getId());
} else {
throw new SQLException("Data Incomplete : category field null");
}
return statement.executeUpdate();
}
@Override
public int update(int id, Product product) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int delete(int id) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Product findById(int id) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<Product> findAll() throws SQLException {
String sql = "SELECT p.product_id,p.name,p.description,p.price,p.expireddate,p.category_id,c.name as category_name "
+ " FROM product p INNER JOIN category c ON (p.category_id = c.category_id)";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
List<Product> result = new ArrayList<Product>();
while (rs.next()) {
Category cat = new Category();
cat.setId(rs.getInt("category_id"));
cat.setName(rs.getString("category_name"));
Product p = new Product();
p.setCategory(cat);
p.setId(rs.getInt("product_id"));
p.setName(rs.getString("name"));
p.setDescription(rs.getString("description"));
p.setPrice(rs.getDouble("price"));
p.setExpiredDate(rs.getDate("expireddate"));
result.add(p);
}
return result;
}
@Override
public List<Product> findByName(String name) throws SQLException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment