JSP - Checking if item is already in Cart - java

I would like to know how I can check if the item I clicked on is already in my Cart.
I used to make a table for that with jSessions and call with each "ADD TO CART" an Insert-Function to add it to the cart. Now I would like to have a 'smart' cart where I add the number I've chosen to the old value in the cart table via UPDATE.
That's what I got. I know I have to iterate somehow in the "if"-Function if the item is already in the cart-table, but f.e. (jSessionID == rsSelect.getString("jSession") AND productID == rsSelect.getInt("id")) won't work.
try {
// If item is already in jSession based Cart...
if (...) {
// change the value of set.
String sqlUpdate = "UPDATE `Cart` SET value = value + '"+set+"' WHERE productID ='"+id+"' AND jSession = '"+jSessionID+"'";
// PrepareStat. Object
PreparedStatement psUpdate = con.prepareStatement(sqlUpdate);
// Update set
psUpdate.executeUpdate();
} else {
// INSERT-Command for new Item
String sqlInsert = "INSERT INTO `Cart` (jSession, produktID, name, value, Preis) values('"+jSessionID+"','"+id+"','"+title+"','"+set+"','"+price+"')";
// PS-Statement
PreparedStatement psInsert = con.prepareStatement(sqlInsert);
// Insert new Item to Cart
psInsert.executeUpdate();
}
} catch(Exception e) {
e.printStackTrace();
}

You can do a select to search to find the existing items.
SELECT productId FROM cart
WHERE productID = ? AND jSession = ?
If this returns a tuple then you got a match.

Related

How to get value from reference table based on foreign key?

I have two tables with the foreign key relating them:
enter image description here
I have used a SQL query to retrieve the value form both tables:
User u = new User();
String sql = "SELECT * FROM user INNER JOIN account ON user.id = account.user WHERE user.id = 1 ";
try {
Statement stm = con.createStatement();
ResultSet rsu = stm.executeQuery(sql);
while(rsu.next()){
u.setFname(rsu.getString("fname"));
u.setLname(rsu.getString("lname"));
u.setMname(rsu.getString("mname"));
u.setGender(rsu.getString("gender"));
u.setAddress(rsu.getString("address"));
u.setCitizenship(rsu.getLong("citizenship"));
/**
*
* Here i want to get values of account table and set it on
* user object to return u
*
*/
}
return u;
} catch (SQLException e) {
e.printStackTrace();
}
It is easy to get the values of table. All you need to do is provide the column name of account table which you already got in your ResultSet.
u.setAccountID(rsu.getLong("accId"));
Here account id is stored in Result set object which you already retrieved from database in result set
1) Include account data in your SQL like so:
SELECT user.*, account.* FROM user INNER JOIN account ON user.id = account.user WHERE user.id = 1
2) Access account field just like user fields:
u.setAccountType(rsu.getString("accountType"));
u.setAccountNo(rsu.getString("accountNo"));
3) Make sure to close Statement in finally block.
4) You dont need to iterate the whole result set since you are expecting only one record. Just replace while with if.

DynamoDB get single column list of range keys or global secondary

I have a DynamoDB table that contains videos info.
Currently "videoID"is the primary (hash) key and "Category" is the range (sort) key.
I want to get a list of all of the "Categories" (Range keys) so I can allow the user to select from one of the available video categories.
https://www.quora.com/What-are-some-good-ways-to-extract-one-single-column-from-a-DynamoDB-table
I was reading that if you modified change the attribute "Category" to a global secondary index you can return the items for that GSI. But I have not been able to find how to do that.
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSIJavaDocumentAPI.html
So I guess that gives me three questions:
Is there a way to do to find the items in Category by querying just the range key?
If change Category to a GSI can I fiind the items that way?
or
Is the only way of doing it scanning the whole table?
Thanks in advance for your help
Is the only way of doing it scanning the whole table?
-NO, you can implement GSI to avoid it
Is there a way to do to find the items in Category by querying just the range key?
- Yes, If you don't want to scan entire table then you need to create GSI which will have Category as Hash. This GSI will act as a table in itself and you can query on it by passing category values.
If change Category to a GSI can I find the items that way?
-Yes, you can query on GSI with category values
I was reading that if you modified change the attribute "Category" to a global secondary index you can return the items for that GSI. But I have not been able to find how to do that.
-You need to create GSI when you create table, example is given in the link that you have specified once that is done you can query that GSI
References:http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
Here is the sample code to create Videos table with GSI.
Create "Videos" table with GSI:-
#Autowired
private AmazonDynamoDBClient dynamoDBClient;
public Boolean createTableWithGlobalSecondaryIndex(String tableName) {
CreateTableRequest createTableRequest = null;
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
try {
ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition().withAttributeName("videoid").withAttributeType("S"));
attributeDefinitions.add(new AttributeDefinition().withAttributeName("category").withAttributeType("S"));
ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>();
keySchema.add(new KeySchemaElement().withAttributeName("videoid").withKeyType(KeyType.HASH));
keySchema.add(new KeySchemaElement().withAttributeName("category").withKeyType(KeyType.RANGE));
// Initial provisioned throughput settings for the indexes
ProvisionedThroughput ptIndex = new ProvisionedThroughput().withReadCapacityUnits(150L)
.withWriteCapacityUnits(150L);
GlobalSecondaryIndex videoCategoryGsi = new GlobalSecondaryIndex().withIndexName("VideoCategoryGsi")
.withProvisionedThroughput(ptIndex)
.withKeySchema(new KeySchemaElement().withAttributeName("category").withKeyType(KeyType.HASH),
new KeySchemaElement().withAttributeName("videoid").withKeyType(KeyType.RANGE))
.withProjection(new Projection().withProjectionType(ProjectionType.ALL));
createTableRequest = new CreateTableRequest().withTableName(tableName).withKeySchema(keySchema)
.withAttributeDefinitions(attributeDefinitions)
.withProvisionedThroughput(
new ProvisionedThroughput().withReadCapacityUnits(100L).withWriteCapacityUnits(100L))
.withGlobalSecondaryIndexes(videoCategoryGsi);
Table table = dynamoDB.createTable(createTableRequest);
table.waitForActive();
} catch (ResourceInUseException re) {
if (re.getErrorMessage().equalsIgnoreCase("Cannot create preexisting table")) {
LOGGER.info("Table already exists =============>" + tableName);
} else if (re.getErrorMessage().contains("Table already exists")) {
LOGGER.info("Table already exists =============>" + tableName);
LOGGER.info("Message =============>" + re.getErrorCode() + ";" + re.getErrorMessage());
} else {
throw new RuntimeException("DynamoDB table cannot be created ...", re);
}
} catch (Exception db) {
throw new RuntimeException("DynamoDB table cannot be created ...", db);
}
return true;
}
Query GSI by category:-
Here is the input is just category and it is querying using GSI. In other words, it is not scanning the entire table as well.
public List<String> findVideosByCategoryUsingGlobalSecondaryIndex(String category) {
List<String> videoAsJson = new ArrayList<>();
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
Table table = dynamoDB.getTable("Videos");
Index index = table.getIndex("VideoCategoryGsi");
ItemCollection<QueryOutcome> items = null;
QuerySpec querySpec = new QuerySpec();
querySpec.withKeyConditionExpression("category = :val1")
.withValueMap(new ValueMap()
.withString(":val1", category));
items = index.query(querySpec);
Iterator<Item> pageIterator = items.iterator();
while (pageIterator.hasNext()) {
String videoJson = pageIterator.next().toJSON();
System.out.println("Video json ==================>" + videoJson);
videoAsJson.add(videoJson);
}
return videoAsJson;
}

Set the selected Jtree Node to JTable

The function need to be accomplished is:
Select main group
Select from sub-group (TEST NAME)
Click >> button which means move the selection to Jtable
Show the slected (Test) with corresponding price on Jtable
conditions:
if the selected node (test name) alread has been selected and added to the Jtable show message say: Test name already added.
we can select and add many test name
Demo image
impotant to say that JTree data come from two tables main-group and sub-group
Here the code: of >> button
try {
DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode) TestTree.getSelectionPath().getLastPathComponent();
Object[] row = {selectedElement};
DefaultTableModel model = (DefaultTableModel) myTests_table.getModel();
System.out.println(String.valueOf(row).toString() + "Hi");
if (selectedElement.isLeaf() == true) {
//model.addRow(row);
// retrive date from DB price
String sql = "SELECT sub_group.name AS 'name', sub_group.price AS 'price'"
+ "FROM sub_group \n"
+ "where sub_group.name = '" + row + "' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
while (rs.next()) {
myTests_table.setModel(DbUtils.resultSetToTableModel(rs));
}
} else {
JOptionPane.showMessageDialog(null, "Please Choose Test name!", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
Dears
where is the error?
Thanks
Add a TreeSelectionListener to your JTree, as shown here. In the listener, update the TableModel of your JTable; the listening table will update itself accordingly, when your implementation of setValueAt() fires the relent TableModelEvent. Your table model should extend AbstractTableModel, as shown here, and contain a Set<Row>. Your Row class should hold the name and price. If Row implements Comparable<Row>, as shown in the example cited here, then Set<Row> will automatically exclude duplicates when you invoke add().
if the issue is that the new TableModel is not being reflected in the UI, use tableModel.fireTableDataChanged().

How to fetch MySQL data without creating Object from Class in Java

I want to fetch data from MySQL without creating object from class
Normally I do something like
public ArrayList getInventoryByItemId(String ItemId) throws SQLException {
ArrayList list = new ArrayList<Inventory>();
String sql = "SELECT iid, i.uid, item_data, item_id, i.ctime, username, gender FROM Inventory i JOIN user u ON i.uid = u.uid WHERE item_id = '"+ItemId+"'";
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {
a = new Inventory(rset.getInt(1), rset.getInt(2), rset.getString(3), rset.getString(4), rset.getTimestamp(6), rset.getString(7), rset.getString(8));
list.add(a);
}
return list;
}
the problem is because Inventory object does not have user data from the joined user table, I cannot create new Inventory.
I just want to automatically make an object where it has all the data attributes, that I can access using the column name.
Thank You
If I got you problem,
You can create new map(HashMap I reccomend) and put values using column name or index as key.
So, your list will be list of maps.
while (rset.next()) {
a = new HashMap<Integer,Object>();
a.put(1,rset.getInt(1));
..........
list.add(a);
}
Or, If you know exact number of columns, you can user array instead of Map (it will be faster)
Based on what you are saying, I take it that your query is not returning data because the inventory does not have the user data that it is being joined with. You need to modify your query to use a left outer join.
String sql = "SELECT iid, i.uid, item_data, item_id, i.ctime, username, gender FROM Inventory i LEFT JOIN user u ON i.uid = u.uid WHERE item_id = '"+ItemId+"'"
This will allow your query to return Inventory data even if the corresponding User data does not exist.

EJB3, JPA error with More than one result was returned from Query.getSingleResult()

i have new problem with JPA in EJB3
my stacktrace are:
Caused by: javax.persistence.NonUniqueResultException: More than one result was returned from Query.getSingleResult()
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.throwNonUniqueResultException(EJBQueryImpl.java:1207)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getSingleResult(EJBQueryImpl.java:722)
at com.DAO.CartDAO.checkUserID(CartDAO.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1056)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1128)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5292)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:615)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:567)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:157)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:139)
at sun.reflect.GeneratedMethodAccessor206.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797)
at com.sun.ejb.co
i create one commandbutton to use for add item to cart, and i write one method to add item to cart in DB, i was check if userid and itemid != null, item quantity will add to 1, it mean when i have userid 1 add itemid 1 into cart, my method will check if it existed, item quantity will add 1 to item quantity in cart table, i can do it with one item, but if i add more item two into cart, it mean i add itemid is 2 into cart table, next i add more quantity of itemid 1 into db it throw exception More than one result. . .
i know it can't have two instance at the same time, but i don't know how to solve it?
Please help me
my addTocart method
public void addtoCart(Items item){
this.items = item;
if(cartDAO.checkUserID(getMemberLoginController().getUser().getUserid()) != null &&
cartDAO.checkItemid(items.getItemid()) != null){
cart = cartDAO.checkUserID(getMemberLoginController().getUser().getUserid());
int updateQuantity = cart.getCartQuantity() + 1;
cart.setCartQuantity(updateQuantity);
// chuyen so luong sang kieu du lieu big decimal
java.math.BigDecimal bigQuantity = new java.math.BigDecimal(String.valueOf(updateQuantity));
// so tien cua san pham = so luong x don gia
BigDecimal updatePrice = items.getPrice().multiply(bigQuantity);
cart.setPrice(updatePrice);
cart = cartDAO.updateCart(cart);
}else if(cartDAO.checkUserID(getMemberLoginController().getUser().getUserid()) != null &&
cartDAO.checkItemid(items.getItemid()) == null){
cart = cartDAO.checkUserID(getMemberLoginController().getUser().getUserid());
cartPk.setUserid(getMemberLoginController().getUser().getUserid());
cartPk.setItemid(item.getItemid());
cart.setCartPK(cartPk);
cart.setCartQuantity(1);
cart.setPrice(item.getPrice());
cart = cartDAO.addCart(cart);
}else {
cartPk.setItemid(item.getItemid());
cartPk.setUserid(getMemberLoginController().getUser().getUserid());
cart.setCartPK(cartPk);
cart.setCartQuantity(1);
cart.setPrice(item.getPrice());
cart = cartDAO.addCart(cart);
}
}
my select statement
#NamedQuery(name = "Cart.findByUserid", query = "SELECT c FROM Cart c WHERE c.cartPK.userid = :userid")
my checkuseridMethod
public Cart checkUserID(int id){
Cart cart = null;
try {
Query query = em.createNamedQuery("Cart.findByUserid");
query.setParameter("userid", id);
return (Cart) query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
Well, it seems like your database has more carts for this user (which is a plausible scenario if you store user history)
You can either make sure that there is no more than one record in the database (by deleting older carts when a new one is created, for example), or use Query.setMaxResults(1) and something like ORDER BY dateCreated in your query.

Categories