WebApplication made using Struts keeps inserting null values to the database - java

I'm working on a sample user-based java web application. When I try to add a user via registration to my database. After capturing the data on the front end, the records get stored as null values
i.e a row of my users table would contain the values (7, null, null, null, null) (using template id(primary-key), f_name, l_name, email, password).
Below are the files I believe could cause possible problems
User.java
package com.ysg.data;
import com.ysg.service.PasswordEncrypter;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;
public class User implements Serializable {
private String id;
private String password;
private String firstName;
private String lastName;
private String email;
public User(){
// default
}
public User( String password, boolean isEncrypted, String firstName, String
lastName, String email){
this.password = isEncrypted ? password : encrypt(password);
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
} //getters and setters follow
UserRepository.java
package com.ysg.repository;
import com.ysg.data.User;
import com.ysg.exception.DuplicateItemException;
import com.ysg.exception.RepositoryException;
import com.ysg.util.MySQLHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class UserRepository implements RepositoryInt<User> {
private static final String INSERT = "INSERT INTO ysg.users (f_name, l_name, email, password) values (?, ?, ?, ?)";
private static final String USER_LOGIN = "SELECT * FROM ysg.users WHERE email=? and password=?";
private static final String USER_FETCH = "SELECT * FROM ysg.users WHERE email='";
private static final String FIRSTNAME = "f_name";
private static final String LASTNAME = "l_name";
private static final String EMAIL= "email";
private static final String PASSWORD = "password";
public UserRepository(){
// default
}
#Override
public User login(User obj){
User result = find(obj);
if (result != null) {
return result;
}
return null;
}
#Override
public User register(User obj){
if (obj != null && (find(obj) == null)) {
return add(obj);
}
return null;
}
private User add(User user){
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(INSERT);
stmt.setString(1, user.getFirstName());
stmt.setString(2, user.getLastName());
stmt.setString(3, user.getEmail());
stmt.setString(4, user.getPassword());
stmt.execute();
closeStatement(stmt);
return user;
}
catch (SQLException ex) {
if (ex.getMessage().contains("Duplicate")) {
System.out.println("Item with duplicate id already exists in repository");
throw new DuplicateItemException("Item with duplicate id already exists in repository");
}
else {
ex.printStackTrace();
System.out.println("Failed to add item to repository");
throw new RepositoryException(ex);
}
}
finally {
closeConnection(conn);
}
}
private User fetch(User user){
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(USER_FETCH + user.getEmail()+ "'");
ResultSet resultSet = stmt.getResultSet();
User result = marshall(resultSet);
closeStatement(stmt);
return result;
}
catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Failed to fetch item from repository");
throw new RepositoryException(ex);
}
finally {
closeConnection(conn);
}
}
private User find(User user){
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(USER_LOGIN);
stmt.setString(1, user.getEmail());
stmt.setString(2, user.getPassword());
ResultSet resultSet = stmt.executeQuery();
User result = marshall(resultSet);
closeStatement(stmt);
return result;
}
catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Failed to add item to repository");
throw new RepositoryException(ex);
}
finally {
closeConnection(conn);
}
}
private User marshall(ResultSet result) throws RepositoryException, SQLException{
if (result == null) {
return null;
}
User user = null;
if (result.next()) {
// String id = result.getString(ID);
String password = result.getString(PASSWORD);
String firstName = result.getString(FIRSTNAME);
String lastName = result.getString(LASTNAME);
String email = result.getString(EMAIL);
user = new User(password, true, firstName, lastName, email);
}
return user;
}
private Connection getConnection(){
return MySQLHelper.getConnection();
}
private static void closeStatement(Statement stmt){
if (stmt != null) {
try {
stmt.close();
//stmt = null;
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private void closeConnection(Connection conn){
if (conn != null) {
try {
conn.close();
conn = null;
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
MySQLHelper.java
package com.ysg.util;
import com.ysg.data.User;
import com.ysg.exception.DuplicateItemException;
import com.ysg.exception.RepositoryException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class MySQLHelper {
private static final String INSERT_USER = "INSERT INTO users(f_name, l_name, email, password) values (?, ?, ?, ?)";
private static final String USER_FETCH = "SELECT * FROM users WHERE id='";
private static final String FETCH_ALL = "SELECT * FROM users";
private static final String COUNT_ALL_USERS = "SELECT COUNT(*) FROM users";
private static final String DELETE_ALL = "DELETE FROM users";
private static final String ID = "id";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
private static final String FIRSTNAME = "f_name";
private static final String LASTNAME = "l_name";
private static final String DS_NAME = "jdbc/sen301DS";
private static Context envCtx;
private static DataSource ds;
static {
try {
Context ctx = new InitialContext();
envCtx = (Context) ctx.lookup("java:/comp/env");
System.out.println(envCtx);
}
catch (Exception ex) {
System.out.println("ConnectionPool will not be available - only direct connection can be used");
}
}
public static List<User> fetch() throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(FETCH_ALL);
ResultSet resultSet = stmt.getResultSet();
List<User> result = marshall(resultSet);
closeStatement(stmt);
return result;
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
public static User fetch(String id) throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(USER_FETCH + id + "'");
ResultSet resultSet = stmt.getResultSet();
List<User> result = marshall(resultSet);
closeStatement(stmt);
return result.get(0);
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
public static User add(User user){
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(INSERT_USER);
stmt.setString(1, user.getFirstName());
stmt.setString(2, user.getLastName());
stmt.setString(3, user.getEmail());
stmt.setString(4, user.getPassword());
stmt.execute();
closeStatement(stmt);
return user;
}
catch (SQLException ex) {
if (ex.getMessage().contains("Duplicate")) {
System.out.println("Item with duplicate id already exists in repository");
throw new DuplicateItemException("Item with duplicate id already exists in repository");
}
else {
ex.printStackTrace();
System.out.println("Failed to add item to repository");
throw new RepositoryException(ex);
}
}
finally {
closeConnection(conn);
}
}
public static int countusers() throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.execute(COUNT_ALL_USERS);
ResultSet resultSet = stmt.getResultSet();
int count = 0;
if (resultSet.next()) {
count = resultSet.getInt(1);
}
closeStatement(stmt);
return count;
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
public static void reset() throws SQLException{
Connection conn = null;
try {
conn = getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate(DELETE_ALL);
closeStatement(stmt);
}
catch (SQLException ex) {
ex.printStackTrace();
throw ex;
}
finally {
closeConnection(conn);
}
}
private static List<User> marshall(ResultSet result) throws SQLException{
List<User> list = new ArrayList<User>();
if (result == null) {
return list;
}
while (result.next()) {
String firstName = result.getString(FIRSTNAME);
String lastName = result.getString(LASTNAME);
String email = result.getString(EMAIL);
String passwd = result.getString(PASSWORD);
User user = new User(passwd, true, firstName, lastName, email);
list.add(user);
}
return list;
}
private static DataSource getDataSource(){
DataSource ds = null;
try {
ds = (DataSource) envCtx.lookup(DS_NAME);
}
catch (NamingException ex) {
ex.printStackTrace();
throw new RepositoryException("Failed to get DataSource");
}
return ds;
}
public static Connection getConnection(){
Connection con = null;
try {
con = getDataSource().getConnection();
}
catch (SQLException ex) {
ex.printStackTrace();
throw new RepositoryException("Failed to get connection to database server");
}
catch (Exception ex) {
con = getDirectConnection();
}
return con;
}
private static Connection getDirectConnection(){
try {
String conURL = "jdbc:mysql://localhost:3306/ysg?serverTimezone=UTC&useSSL=false&" + "user=sen301&password=sen301";
return DriverManager.getConnection(conURL);
}
catch (SQLException ex) {
ex.printStackTrace();
throw new RepositoryException("Failed to get direct connection to database server");
}
catch (Exception ex) {
ex.printStackTrace();
throw new RepositoryException(ex);
}
}
private static void closeStatement(Statement stmt){
if (stmt != null) {
try {
stmt.close();
stmt = null;
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
private static void closeConnection(Connection conn){
if (conn != null) {
try {
conn.close();
conn = null;
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Related

How to Composition/Association/List of Objects in DAO implementation

A minimum runnable example of my project is above:
Shopping Cart and its Products; I need to save this aggregation in pure JDBC, without ORM, in the Database. Is it the proper way to save the product list to DB, passing to the shopping_cart_fk_id to each product and its DAOs?
MainClass
package ShoppingCartDAO;
import java.util.Scanner;
public class MainClass {
public static void main(String[] args)
{
ShoppingCart shoppingCart = new ShoppingCart();
Integer choice = 0;
Scanner input = new Scanner(System.in);
do {
choice = 0;
System.out.print("Choose one option: \n");
System.out.print("1 - Register New Product \n");
System.out.print("0 - Exit And Save");
choice = input.nextInt();
switch (choice)
{
case 1:
new ShoppingCart().InsertInto(new ProductRegister().RegisterNewProduct());
break;
default:
System.out.print(" Invalid Option \n");
break;
}
} while (choice != 0);
new ShoppingCartDao().add(shoppingCart);
input.close();
}
}
ConnectionFactory
package ShoppingCartDAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class ShoppingCartDao{
public void add(ShoppingCart shoppingCart)
{
try
{
PreparedStatement pstmt = ConnectionFactory.getConnection().prepareStatement("Insert into shoppingCart (date) values (?)");
pstmt.setDate(1, new java.sql.Date(System.currentTimeMillis()));
pstmt.execute();
pstmt.close();
} catch(SQLException e)
{
throw new RuntimeException(e);
}
ProductDao productDAO = new ProductDao();
for(Product product : shoppingCart.getProduct()){
productDAO.add(product);
}
}
public Integer getCount()
{
Integer count;
try
{
Statement stmt = ConnectionFactory.getConnection().createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) AS recordCount FROM shoppingcart");
rs.next();
count = rs.getInt(1);
rs.close();
stmt.close();
} catch(SQLException e)
{
throw new RuntimeException(e);
}
return count;
}
}
ShoppingCart Entity
public class ShoppingCart
{
Long id;
Date date;
ArrayList<Product>products = new ArrayList<Product>();
public ShoppingCart(){
this.date = new Date();
}
public void InsertInto(Product product){
products.add(product);
}
public Date getDate(){
return this.buyDate;
}
public ArrayList<Product>getProduct(){
return this.products;
}
}
Product Entity
public class Product
{
String name = new String();
Integer quantity = new Integer();
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setQuantity(Integer quantity){
this.quantity = quantity;
}
public Integer getQuantity(){
return this.quantity;
}
}
Shopping Cart DAO
package ShoppingCartDAO;
import java.util.ArrayList;
import java.util.Date;
public class ShoppingCart {
Long id;
Date date;
ArrayList<Product>products = new ArrayList<Product>();
public ShoppingCart(){
this.date = new Date();
}
public void InsertInto(Product product){
products.add(product);
}
public Date getDate(){
return this.date;
}
public ArrayList<Product>getProduct(){
return this.products;
}
public void addProduct(Product product) {
products.add(product);
}
}
ProductDAO
package ShoppingCartDAO;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ProductDao {
public void add(Product product)
{
try
{
String query = "Insert into product (fkShoppingCartId, name, quantity) values (?, ?, ?)";
PreparedStatement pstmt = ConnectionFactory.getConnection().prepareStatement(query);
pstmt.setLong(1, new ShoppingCartDao().getCount() + 1);
pstmt.setString(2, product.getName());
pstmt.setInt(3, product.getQuantity());
pstmt.execute();
pstmt.close();
}
catch(SQLException e)
{
throw new RuntimeException(e);
}
}
You have a Java model for your data, what database schema do you need to store it?
It's pretty obvious for the simple types like numbers and strings; for the List of products in your ShoppingCart, I assume you want to conserve the order of the Products in you ShoppingCart. I also assume that a Product is in fact an item in a ShoppingCart since it has a quantity field; so a Product has no existence of it's own: it's a part of a ShoppingCard.
With these assumptions, I can represent the Java model in the database with two tables:
SHOPPING_CART(ID, DATE)
PRODUCT(SHOPPING_CART_ID, POS, NAME, QUANTITY)
and then define class ShoppingCartPersistence:
public class ShoppingCardPersistence {
private final Connection connection;
private final ProductPersistence productPersistence;
public ShoppingCardPersistence(Connection connection) {
this.connection = connection;
this.productPersistence = new ProductPersistence(connection);
}
public void create(ShoppingCart cart) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(
"INSERT INTO SHOPPING_CART(ID, DATE) VALUES(?, ?)")) {
stmt.setLong(1, cart.getId());
stmt.setTimestamp(2, new Timestamp(cart.getDate().getTime()));
stmt.executeUpdate();
}
productPersistence.create(cart.getId(), cart.getProducts());
}
public ShoppingCart read(long id) throws SQLException {
ShoppingCart cart;
try (PreparedStatement stmt = connection.prepareStatement(
"SELECT DATE FROM SHOPPING_CART WHERE ID=?")) {
stmt.setLong(1, id);
ResultSet rs = stmt.executeQuery();
if (!rs.next()) {
return null;
}
cart = new ShoppingCart();
cart.setId(id);
cart.setDate(new Date(rs.getTimestamp(1).getTime()));
}
cart.setProducts(productPersistence.read(cart.getId()));
return cart;
}
public void update(ShoppingCart cart) throws SQLException {
productPersistence.delete(cart.getId());
try (PreparedStatement stmt = connection.prepareStatement(
"UPDATE SHOPPING_CART SET DATE=? WHERE ID=?")) {
stmt.setLong(2, cart.getId());
stmt.setTimestamp(1, new Timestamp(cart.getDate().getTime()));
stmt.executeUpdate();
}
productPersistence.create(cart.getId(), cart.getProducts());
}
public void delete(ShoppingCart cart) throws SQLException {
productPersistence.delete(cart.getId());
try (PreparedStatement stmt = connection.prepareStatement(
"DELETE SHOPPING_CART WHERE ID=?")) {
stmt.setLong(1, cart.getId());
stmt.executeUpdate();
}
}
}
and ProductPersistence:
public class ProductPersistence {
private final Connection connection;
public ProductPersistence(Connection connection) {
this.connection = connection;
}
public void create(long id, List<Product> products) throws SQLException {
if (!products.isEmpty()) {
try (PreparedStatement stmt = connection.prepareStatement(
"INSERT INTO PRODUCT(SHOPPING_CART_ID, POS, NAME, QUANTITY)"
+ " VALUES(?,?,?,?)")) {
for (int i = 0; i < products.size(); ++i) {
Product prod = products.get(i);
stmt.setLong(1, id);
stmt.setInt(2, i);
stmt.setString(3, prod.getName());
stmt.setInt(4, prod.getQuantity());
stmt.addBatch();
}
stmt.executeBatch();
}
}
}
public List<Product> read(long id) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(
"SELECT POS, NAME, QUANTITY FROM PRODUCT"
+ " WHERE SHOPPING_CART_ID=?"
+ " ORDER BY POS")) {
List<Product> result = new ArrayList<>();
stmt.setLong(1, id);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Product prod = new Product();
prod.setQuantity(rs.getInt(2));
prod.setName(rs.getString(3));
result.add(prod);
}
return result;
}
}
public void delete(long id) throws SQLException {
try (PreparedStatement stmt = connection.prepareStatement(
"DELETE PRODUCT WHERE SHOPPING_CART_ID=?")) {
stmt.setLong(1, id);
stmt.executeUpdate();
}
}
}
You would typically use these classes with a piece of code like this:
try (Connection connection = ConnectionFactory.getConnection()) {
ShoppingCartPersistence pm
= new ShoppingCartPersistence(connection);
ShoppingCart cart = pm.read(shoppingCardId);
// do a lot of useful thing with the cart
pm.update(cart);
connection.commit();
} catch (SQLException ex) {
ex.printStackTrace();
}
Note that in your ConnectionFactory you should disable autocommit.
The ID of a shopping card has to be assigned before a call to ShoppingCardPersistence.create but databases offer mechanisms to automatically generate them, either with an autoincremented column or with a sequence.

ResultSet.next() is false. Even though table is not empty

I'm using Oracle 19c database. And HOMESQUAD_EMPLOYEE is table with columns : EMP_ID,EMP_NAME,EMP_MOBILE_NO,EMP_PASSWORD with VARCHAR2(50).
I'm trying to retrieve the row with given EMP_MOBILE_NO in Java using ResultSet object .
Connection is established successfully. PreparedStatement is getting executed successfully,ResultSet is not null but ResultSet.next() is null.
The same query is getting executed and I'm getting required row.
Here's the Code and its output.
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
//Loading Driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Loading Connection
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/orcl", dbUsername, dbPassword);
//Executing query;
System.out.println("Connection Established");
//Object to store result
items = new ArrayList < Object > ();
Map properties={ActionType=ProcessLogin, mobileNo=8308856606};
queryString=buildLoginQuery(properties);
System.out.println("Query: " + queryString);
if (queryString != null && !queryString.trim().equals("")) {
System.out.println("Into P Statement If Loop");
pstmt = con.prepareStatement(queryString);
System.out.println("StateMent Prepared: " + pstmt.toString());
rs = pstmt.executeQuery();
System.out.println("Query Executed");
System.out.println("Result Set rs.next():" + rs.next()); //Error Point
while (rs != null && rs.next()) {
items.add(constructLoginProps(rs));
}
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
}
} catch (Exception e) {
System.out.println("Exception Occured in aDBExecute:" + e.getMessage());
}
//constructLoginProps Function
private HomesquadEmployee constructLoginProps(ResultSet rs) {
HomesquadEmployee vo = new HomesquadEmployee();
try {
if (rs.getString("EMP_PASSWORD") != null) {
vo.setEmpPassword(rs.getString("EMP_PASSWORD"));
}
if (rs.getString("EMP_ID") != null) {
vo.setEmpId(rs.getString("EMP_ID"));
}
if (rs.getString("EMP_NAME") != null) {
vo.setEmpName(rs.getString("EMP_NAME"));
}
if (rs.getString("EMP_MOBILE_NO") != null) {
vo.setEmpMobileNo(rs.getString("EMP_MOBILE_NO"));
}
} catch (Exception e) {
System.out.println("Exception Occured in buildLoginQuery: " + e.getMessage());
}
return (vo);
}
//HomesquadEmployee Class
public class HomesquadEmployee {
private String empId;
private String empName;
private String empMobileNo;
private String empPassword;
public HomesquadEmployee() {}
public HomesquadEmployee(String empId, String empName, String empMobileNo, String empPassword) {
this.empId = empId;
this.empName = empName;
this.empMobileNo = empMobileNo;
this.empPassword = empPassword;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpMobileNo() {
return empMobileNo;
}
public void setEmpMobileNo(String empMobileNo) {
this.empMobileNo = empMobileNo;
}
public String getEmpPassword() {
return empPassword;
}
public void setEmpPassword(String empPassword) {
this.empPassword = empPassword;
}
}
//build Query Function
private String buildLoginQuery(Map properties) throws Exception {
String mobileNo="";
String password="";
queryString="SELECT * FROM HOMESQUAD_EMPLOYEE ";
if(properties!=null && (String)properties.get("mobileNo")!=null) {
mobileNo=((String)properties.get("mobileNo")).trim();
queryString=queryString+" WHERE EMP_MOBILE_NO = "+"'"+mobileNo.toUpperCase()+"'";
}
return(queryString);
}
Output:
Connection Established.
Query: SELECT * FROM HOMESQUAD_EMPLOYEE WHERE EMP_MOBILE_NO = '8308856606'
Into P Statement If Loop
StateMent Prepared: oracle.jdbc.driver.OraclePreparedStatementWrapper#514f51cf
Query Executed
Result Set rs.next():false
Please help me out.

Mockito datasource test fail in debug mode

Why is this unit test failing when I run it in Debug mode using a break-point at the line
while (rs.next()) {.
It will exit the loop after the first iteration despite the instruction in the test.
Mockito.when(mockResultSet.next()).thenReturn(true, true, false);
this unit test works fine when running it in normal mode.
note: I am using Intellij, testNG.
Class
public class ProjectDao {
private static Logger LOG = LogManager.getLogger(ProjectDao.class);
private DataSource dataSource;
private int id;
private String name;
// For Testing
public ProjectDao(DataSource dataSource) {
this.dataSource = dataSource;
}
public ProjectDao() {
dataSource = Database.getDataSource();
}
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 List<Project> getProjects() throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String SQL = "SELECT project.id, project.name FROM cicd.project";
List<Project> projects = new ArrayList<>();
try {
conn = dataSource.getConnection();
ps = conn.prepareStatement(SQL);
rs = ps.executeQuery();
while (rs.next()) {
Project p = new Project();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
projects.add(p);
}
LOG.debug("found: " + projects);
return projects;
} catch (SQLException e) {
LOG.error("Error: " + e.getMessage());
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
LOG.error("Error closing resultset: " + e.getMessage());
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
LOG.error("Error closing PreparedStatement: " + e.getMessage());
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
LOG.error("Error closing connection: " + e.getMessage());
e.printStackTrace();
}
}
}
return projects;
}
Test class
#PrepareForTest(ProjectDao.class)
public class ProjectDaoTests {
private static Logger LOG = LogManager.getLogger(ProjectDaoTests.class);
List<Project> projects;
Project projectA = new Project();
Project projectB = new Project();
#Mock
DataSource mockDataSource;
#Mock
Connection mockConn;
#Mock
PreparedStatement mockPreparedStmnt;
#Mock
ResultSet mockResultSet;
#BeforeTest(groups = "ut")
public void initMocks() throws IOException, SQLException {
MockitoAnnotations.initMocks(this);
when(mockDataSource.getConnection()).thenReturn(mockConn);
when(mockDataSource.getConnection(anyString(), anyString())).thenReturn(mockConn);
doNothing().when(mockConn).commit();
when(mockConn.prepareStatement(anyString())).thenReturn(mockPreparedStmnt);
when(mockPreparedStmnt.executeQuery()).thenReturn(mockResultSet);
projects = new ArrayList<>();
}
#Test(groups = "ut")
public void testProjects() throws Exception {
projectA.setId(1);
projectA.setName("projectA");
projectB.setId(2);
projectB.setName("projectB");
projects.add(projectA);
projects.add(projectB);
Mockito.when(mockResultSet.next()).thenReturn(true, true, false);
Mockito.when(mockResultSet.getInt("id")).thenReturn(projectA.getId(), projectB.getId());
Mockito.when(mockResultSet.getString("name")).thenReturn(projectA.getName(), projectB.getName());
ProjectDao projectDao = new ProjectDao(mockDataSource);
List<Project> projectsList = projectDao.getProjects();
Assert.assertEquals(projectsList.size(), 2);
Assert.assertEquals(projectsList.get(0).getId(), projectA.getId());
Assert.assertEquals(projectsList.get(0).getName(), projectA.getName());
Assert.assertEquals(projectsList.get(1).getId(), projectB.getId());
Assert.assertEquals(projectsList.get(1).getName(), projectB.getName());
}

Trying to display all data from database table into Jtable using reflection

I'm trying to display all the data from different database table into a JTable using reflection but when i run the code I gen this kind of error:. The methods responsible for that are createViewAllQuery, ViewAll and createObjects from AbstractDAO class.
Any idea what the problem is? Thanks!
package project3;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.mysql.jdbc.PreparedStatement;
public class AbstractDAO<T>{
protected static final Logger LOGGER = Logger.getLogger(AbstractDAO.class.getName());
private final Class<T> type;
#SuppressWarnings("unchecked")
public AbstractDAO() {
this.type = (Class<T>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
private String createFindQuery(String field) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
sb.append(" * ");
sb.append(" FROM ");
sb.append(type.getSimpleName());
sb.append(" WHERE " + field + "=?");
return sb.toString();
}
private String createAddQuery(T object) throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO ");
sb.append(type.getSimpleName());
sb.append(" VALUES (");
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
if(field.get(object) instanceof Integer) {
sb.append(field.get(object));
sb.append(",");
}
else {
sb.append("'");
sb.append(field.get(object));
sb.append("',");
}
}
sb.deleteCharAt(sb.length()-1);
sb.append(");");
System.out.println(sb.toString());
return sb.toString();
}
private String createViewAllQuery() throws IllegalArgumentException, IllegalAccessException {
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM ");
sb.append(type.getSimpleName());
sb.append(";");
return sb.toString();
}
public List<T> ViewAll() throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createViewAllQuery();
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public JTable createTable(List<T> objects) throws IllegalArgumentException, IllegalAccessException {
ArrayList<String> columnNamesArrayList = new ArrayList<String>();
for(Field field : objects.get(0).getClass().getDeclaredFields()) {
field.setAccessible(true);
columnNamesArrayList.add(field.getName());
}
String[] columnNames = new String[columnNamesArrayList.size()];
columnNames = columnNamesArrayList.toArray(columnNames);
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
Iterator<T> i = objects.iterator();
while(i.hasNext()) {
T object = i.next();
ArrayList<Object> columnDataAsArrayList = new ArrayList<Object>();
for(Field field : object.getClass().getDeclaredFields()) {
field.setAccessible(true);
columnDataAsArrayList.add(field.get(object));
}
Object[] columnDataAsArray = new Object[columnDataAsArrayList.size()];
columnDataAsArray = columnDataAsArrayList.toArray(columnDataAsArray);
tableModel.addRow(columnDataAsArray);
}
JTable table = new JTable(tableModel);
return table;
}
public void add(T object) throws IllegalArgumentException, IllegalAccessException {
Connection connection = null;
PreparedStatement statement = null;
String query = createAddQuery(object);
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.executeUpdate();
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
}
public List<T> findByFirstName(String firstName) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("first_name");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, firstName);
resultSet = statement.executeQuery();
return createObjects(resultSet);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findByFirstName " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
public T findById(int id) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
String query = createFindQuery("id");
try {
connection = ConnectionFactory.getConnection();
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setInt(1, id);
resultSet = statement.executeQuery();
return createObjects(resultSet).get(0);
} catch(SQLException e) {
LOGGER.log(Level.WARNING, type.getName() + "DAO:findById " + e.getMessage());
} finally {
ConnectionFactory.close(resultSet);
ConnectionFactory.close(statement);
ConnectionFactory.close(connection);
}
return null;
}
private List<T> createObjects(ResultSet resultSet){
List<T> list = new ArrayList<T>();
try {
try {
while(resultSet.next()) {
T instance = type.newInstance();
for(Field field: type.getDeclaredFields()) {
Object value = resultSet.getObject(field.getName());
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), type);
Method method = propertyDescriptor.getWriteMethod();
method.invoke(instance, value);
}
list.add(instance);
}
} catch (IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException | SQLException | IntrospectionException e) {
e.printStackTrace();
}
}catch(InstantiationException e) {
e.printStackTrace();
}
return list;
}
}
package project3;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.text.html.HTMLDocument.Iterator;
public class ProductsDAO extends AbstractDAO<Products>{
public ProductsDAO() {};
public static void main(String[] args) {
ProductsDAO p1 = new ProductsDAO();
//Products product1 = new Products(3, "cascaval", 5, " tip de branza facuta din lapte de vaca sau oaie", 4680);
try {
JTable table = new JTable();
table = p1.createTable(p1.ViewAll());
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
/*List<Products> list = new ArrayList<Products>();
list = p1.ViewAll();
java.util.Iterator<Products> i = list.iterator();
while(i.hasNext()) {
Products x = i.next();
System.out.println(x.getDescription());
}*/
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Here is one of the classes:
package project3;
public class Products {
private int id;
private String name;
private int price;
private String description;
private int stoc;
public Products(int id, String name, int price, String description, int stoc) {
super();
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.stoc = stoc;
}
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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getStoc() {
return stoc;
}
public void setStoc(int stoc) {
this.stoc = stoc;
}
}
Your class Products hasn't got a default-constructor (so no method <init>), but you're trying to use that in
T instance = type.newInstance();
Since the Method isn't there the NoSuchMethodException is thrown.
You either have to add a default-constructor like
public Products() {
...
}
or call the constructor with arguments (probably harder to do ;)

Database not updating with thymeleaf and JDBC

I have a problem with my code as to where I can insert new players but I can't update them for some reason. Here is the code for my Controller and class where I keep all the methods. I am just trying to edit the camper but I am not sure as to why it's not updating them in the database at all. I can post more code if needed, just wasn't sure what was needed.
Controller:
package info.hccis.camper.web;
import info.hccis.camper.bo.CamperValidationBO;
import info.hccis.camper.dao.CamperDAO;
import info.hccis.camper.model.jpa.Camper;
import info.hccis.camper.model.jpa.User;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class CamperController {
#RequestMapping("/camper/add")
public String add(Model model, HttpSession session) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
Camper camper = new Camper();
model.addAttribute("camper", camper);
return "camper/add";
}
#RequestMapping("/camper/delete")
public String delete(Model model, HttpSession session, HttpServletRequest request) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
String id = request.getParameter("id");
CamperDAO.delete(Integer.parseInt(id));
ArrayList<Camper> campers = CamperDAO.selectAll();
model.addAttribute("campers", campers);
return "camper/list";
}
#RequestMapping("/camper/edit")
public String edit(Model model, HttpSession session, HttpServletRequest request){
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
String id = request.getParameter("id");
Camper camper = CamperDAO.select(Integer.parseInt(id));
model.addAttribute("camper", camper);
return "camper/add";
}
#RequestMapping("/camper/addSubmit")
public String addSubmit(Model model, #ModelAttribute("camper") Camper camper, HttpSession session) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
ArrayList<String> errors = CamperValidationBO.validateCamper(camper);
//If there is an error send them back to add page.
boolean error = false;
if (!errors.isEmpty()) {
error = true;
}
if (error) {
model.addAttribute("messages", errors);
return "/camper/add";
}
System.out.println("BJM - About to add " + camper + " to the database");
try {
CamperDAO.update(camper);
//Get the campers from the database
ArrayList<Camper> campers = CamperDAO.selectAll();
model.addAttribute("campers", campers);
} catch (Exception ex) {
System.out.println("BJM - There was an error adding camper to the database");
}
return "camper/list";
}
#RequestMapping("/camper/list")
public String showHome(Model model, HttpSession session) {
//make sure logged in
User user = (User) session.getAttribute("loggedInUser");
if (user == null) {
model.addAttribute("user", new User());
return "other/welcome";
}
//Get the campers from the database
ArrayList<Camper> campers = CamperDAO.selectAll();
System.out.println("BJM-found " + campers.size() + " campers. Going to welcome page");
model.addAttribute("campers", campers);
//This will send the user to the welcome.html page.
return "camper/list";
}
}
Other Class:
package info.hccis.camper.dao;
import info.hccis.camper.dao.util.ConnectionUtils;
import info.hccis.camper.dao.util.DbUtils;
import info.hccis.camper.model.jpa.Camper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.logging.Logger;
public class CamperDAO {
private final static Logger LOGGER = Logger.getLogger(CamperDAO.class.getName());
public static synchronized void delete(int idIn) {
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
try {
conn = ConnectionUtils.getConnection();
sql = "delete FROM camper where id = ? limit 1";
ps = conn.prepareStatement(sql);
ps.setInt(1, idIn);
ps.executeUpdate();
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
}
public static Camper select(int idIn) {
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
Camper theCamper = null;
try {
conn = ConnectionUtils.getConnection();
sql = "SELECT * FROM camper WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setInt(1, idIn);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
long id = rs.getInt("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String dob = rs.getString("dob");
String parentName = rs.getString("parentName");
String email = rs.getString("email");
double totalPaid = rs.getDouble("totalPaid");
theCamper = new Camper(id, firstName, lastName, parentName, email, totalPaid);
theCamper.setDob(dob);
}
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
return theCamper;
}
public static ArrayList<Camper> selectAll() {
ArrayList<Camper> campers = new ArrayList();
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
try {
conn = ConnectionUtils.getConnection();
sql = "SELECT * FROM camper order by id";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
long id = rs.getLong("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String dob = rs.getString("dob");
String parentName = rs.getString("parentName");
String email = rs.getString("email");
double totalPaid = rs.getDouble("totalPaid");
Camper camper = new Camper(id, firstName, lastName, parentName, email, totalPaid);
camper.setDob(dob);
campers.add(camper);
}
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
return campers;
}
public static ArrayList<Camper> selectAllByDOB(String year) {
ArrayList<Camper> campers = new ArrayList();
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
try {
conn = ConnectionUtils.getConnection();
sql = "SELECT * FROM camper where dob like ? order by id";
ps = conn.prepareStatement(sql);
ps.setString(1, year+"%");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
long id = rs.getLong("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String dob = rs.getString("dob");
String parentName = rs.getString("parentName");
String email = rs.getString("email");
double totalPaid = rs.getDouble("totalPaid");
Camper camper = new Camper(id, firstName, lastName, parentName, email, totalPaid);
camper.setDob(dob);
campers.add(camper);
}
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
return campers;
}
public static synchronized Camper update(Camper camper) throws Exception {
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
/*
* Setup the sql to update or insert the row.
*/
try {
conn = ConnectionUtils.getConnection();
//Check to see if camper exists.
if (camper.getId() == null) {
sql = "SELECT max(id) from Camper";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
long max = 0;
while (rs.next()) {
max = rs.getInt(1) + 1;
}
camper.setId(max);
sql = "INSERT INTO `Camper`(`id`, `firstName`, `lastName`, `dob`, `parentName`, `email`, `totalPaid`) "
+ "VALUES (?,?,?,?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setLong(1, camper.getId());
ps.setString(2, camper.getFirstName());
ps.setString(3, camper.getLastName());
ps.setString(4, camper.getDob());
ps.setString(5, camper.getParentName());
ps.setString(6, camper.getEmail());
ps.setDouble(7, camper.getTotalPaid());
} else {
sql = "UPDATE `camper` SET `firstName`=?,`lastName`=?,`dob`=?, `parentName`=?, `email`=?, `totalPaid`=? WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setLong(1, camper.getId());
ps.setString(2, camper.getFirstName());
ps.setString(3, camper.getLastName());
ps.setString(4, camper.getDob());
ps.setString(5, camper.getParentName());
ps.setString(6, camper.getEmail());
ps.setDouble(7, camper.getTotalPaid());
}
/*
Note executeUpdate() for update vs executeQuery for read only!!
*/
ps.executeUpdate();
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
throw e;
} finally {
DbUtils.close(ps, conn);
}
return camper;
}
}
your code for update is :
sql = "UPDATE `camper` SET `firstName`=?,`lastName`=?,`dob`=?, `parentName`=?, `email`=?, `totalPaid`=? WHERE id = ?";
ps = conn.prepareStatement(sql);
ps.setLong(1, camper.getId());
ps.setString(2, camper.getFirstName());
ps.setString(3, camper.getLastName());
ps.setString(4, camper.getDob());
ps.setString(5, camper.getParentName());
ps.setString(6, camper.getEmail());
ps.setDouble(7, camper.getTotalPaid());
You have 7 parameters and thelast is set to totalPaid valuenstead of id.
You must have:
ps.setString(1, camper.getFirstName());
ps.setString(2, camper.getLastName());
ps.setString(3, camper.getDob());
ps.setString(4, camper.getParentName());
ps.setString(5, camper.getEmail());
ps.setDouble(6, camper.getTotalPaid());
ps.setLong(7, camper.getId());

Categories