I'm using jComboBox to select a Supplier from table so I have created -1 id row in a table for "none" selected Supplier.
-1 row is also appearing to user where I've fetched all records in
jTable.
I don't want user delete this row may either accidentally or consciously.
So may I have something like this?
I'm using MySQL and Java.
String comName = (String) jSupplrsComboBox.getSelectedItem();
Suppliers suppliers = manager.searchSuppCompny(comName);
if (comName.equals("none")) {
receivings.getSuppliers().setId(-1);
receivings.setSuppliers(suppliers);
}
receivings.setSuppliers(suppliers);
Fetched Suppliers to jComboBox and just manually addd "none" text so it doesn't match in Suppliers table.
I'm not sure what exactly you're trying to achieve, but if you're utilizing a JComboBox, I imagine you're filtering your database by the supplier indicated by the comboBox selection. This also means your comboBox model needs to be populated with entries that exist in your database.
This is a quick way to set Strings to the ComboBox from an Enum, passing entries from the database should work in a similar way, but ensuring duplication does not exist may need to be addressed
jSupplrsComboBox.setModel(new DefaultComboBoxModel<>(SupplierId.values()));
From link Java - Check Boxes in a JComboBox, response by Jonathan Feinberg might be better suited for more than one filter.
As for MYSQL, I'm assuming you have access to make modifications, it may be better if you add an extra field, say isValid, to indicate if said entry is valid or not. In which case you can filter on jSupplrsComboBox.getSelectedItem() with an additional WHERE isValid = 1.
But your question was geared more towards Java than MYSQL, so I won't mention more on that. Check out MySQL Boolean Question and associated links for more on that.
Well I tried myself and where I'm retrieving records I changed code:
DefaultTableModel suppliersModel = (DefaultTableModel) jSuppliersTable.getModel();
for(Suppliers suppliers : manager.allSuppliers()) {
suppliersModel.addRow(new Object[]{suppliers.getId()});
int id = (Integer) suppliersModel.getValueAt(0, 0);
if(id == -1) {
suppliersModel.removeRow(0);
}
That retrieve records after first row which is -1 id in the database table.
Tahnks.
Related
I'm relatively new to working with JDBC and SQL. I have two tables, CustomerDetails and Cakes. I want to create a third table, called Transactions, which uses the 'Names' column from CustomerDetails, 'Description' column from Cakes, as well as two new columns of 'Cost' and 'Price'. I'm aware this is achievable through the use of relational databases, but I'm not exactly sure about how to go about it. One website I saw said this can be done using ResultSet, and another said using the metadata of the column. However, I have no idea how to go about either.
What you're probably looking to do is to create a 'SQL View' (to simplify - a virtual table), see this documentation
CREATE VIEW view_transactions AS
SELECT Name from customerdetails, Description from cakes... etc.
FROM customerdetails;
Or something along those lines
That way you can then query the View view_transactions for example as if it was a proper table.
Also why have you tagged this as mysql when you are using sqlite.
You should create the new table manually, i.e. outside of your program. Use the commandline 'client' sqlite3 for example.
If you need to, you can use the command .schema CustomerDetails in that tool to show the DDL ("metadata" if you want) of the table.
Then you can write your new CREATE TABLE Transactions (...) defining your new columns, plus those from the old tables as they're shown by the .schema command before.
Note that the .schema is only used here to show you the exact column definitions of the existing tables, so you can create matching columns in your new table. If you already know the present column definitions, because you created those tables yourself, you can of course skip that step.
Also note that SELECT Name from CUSTOMERDETAILS will always return the data from that table, but never the structure, i.e. the column definition. That data is useless when trying to derive a column definition from it.
If you really want/have to access the DB's metadata programatically, the documented way is to do so by querying the sqlite_master system table. See also SQLite Schema Information Metadata for example.
You should read up on the concept of data modelling and how relational databases can help you with it, then your transaction table might look just like this:
CREATE TABLE transactions (
id int not null primary key
, customer_id int not null references customerdetails( id )
, cake_id int not null references cakes( id )
, price numeric( 8, 2 ) not null
, quantity int not null
);
This way, you can ensure, that for each transaction (which is in this case would be just a single position of an invoice), the cake and customer exist.
And I agree with #hanno-binder, that it's not the best idea to create all this in plain JDBC.
Im having duplicate rows in a table like the printscreen
I read the solution was selecting the columns and check the option: "supress duplicates" (as printscreen) but this is not working as well.
Does anybody has an ideia of how to fix this problem? Thanks in advance
In BIRT, Suppress Duplicates just makes sure the value in the column in not repeated and hence you could see Blank or rows with no values.
And the other reason why we get multiple rows is because there are those many rows with same values.
To avoid blank rows we can make use of hide condition. Steps for the same:
Select the detail row of the table:
Detail Row Selection
In Property Editor -> Properties -> Visibility -> check on Hide Element and add
hidden condition in the pop up window
Row Visibility condition
Visibility condition could be like this :
if(row["Col1"]=="" && row["Col2"]=="" && row["Col3"]==""){true}
If "" doesn't work in the condition, replace it with null
Hope this works.
Thank You.
If you are getting duplicate rows in your table, where it looks like all the values are identical. You probably have one of these issues
A join to a second data set that causes a second row of data to be created, where the filed with two values is not displayed on your report table. = If that field is not required remove it from your dataset.
There are duplicate rows of data in your raw data source = use something like 'select distinct/unique' in your SQL to return only a single row.
If you only have a single data source with only unique rows, what you are displaying may not show a field with two distinct values, but the table is bound to the data that does have two values. Suppress dupes is not going to work because there are not any dupes. = Either display the field with multiple values or clean up your data pull so there is no longer duplicates where they are not intended.
At my application there is a table and I am inserting new rows that table. There is a Java class that gets a row(by a select query) from that table and send it to web part. I want to get the latest row everytime (Ican handle it with getting the row that which has the biggest auto generated id) however I have to check that if I select a row and send it to web part and if there happens no insert when I come to select the latest row I don't want to send any data to web part if that row has been send previously (I mean if that row had retrieved by a select query)
I think that if I put a new column i.e. named as has_sent (that has a value of 0 by default) and if I select that row I can set it to 1 and before I send the data I can check that if that column is 0 or not.
I want to learn that is there any better way to handle that situation?
A row doesn't remember if it has been requested or not, you'll have to use your has_sent column.
In my application I have a JTable and a List.
The List:
The list is populated using a JPA query. The user can re-execute the query by changing attributes in the GUI. Let's assume the query has a named parameter "year" and the user can change this. Then the following happens (simplified by leaving out exception handling):
myList.clear()
mylist.addAll( myQuery.setParameter("year", 2010) )
As the list changes, the binding fires the required handlers and the table now reflects the new dataset.
The JTable:
The contents of the JTable come from a BeansBinding (more precisely a JTableBinding). The binding source is the aforementioned list.
The query is only executed for intensive tasks. Like applying a rough filter on a huge dataset. The earlier example with the year is a good example. This will always return a manageable chunk of data to the client. Now, to have a more responsive user experience, more fine-grained filters happen in the JTable itself. This avoids unnecessary round-trips to the database.
Next, assume the following scenario: A user selects a row in the table and hit's the delete button. If the table has not been filtered the required code is straightforward (again, no error-checking, concurrency locking, and exception handlers for code simplicity):
MyObject = myList.get( myTable.getSelectedRow() );
myEntityManager.getTransaction().begin()
myEntityManager.remove( myObject )
myEntityManager.getTransaction().commit()
However: If the table is filtered on the client side, the table won't reflect the data inside the List. So getSelectedRow() will not return an index which will map to the same entry in the List (I have not tested this, but I beleive I am correct with this assumption?)
So... My question:
How best to solve this?
A possible solution?
I've solved the problem at hand with the following:
I created a new Bean called selectedTableElement which contains a member holding the element which is currently selected in the table.
Next, I created a new binding (source: my table, target: my "selectedElement" bean) using
binding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, myTable, ELProperty.create("${selectedElement}"), selectedTableElement, BeanProperty.create("selectedElement"), "selectedElementBinding");
This solution effectively solves the problem by keeping track of the selected element of the table using Beans Binding.
But is this really necessary? It feels clunky to me. A whole new class only the encapsulate the selected element? Is there no other, more direct way of retrieving the "${selectedElement}" property of the JTable?
I'll try to answer to both your questions.
Regarding the first question (the filtered selected index vs the real list index):
I assume that you bound the table using BeansBinding, via createJTableBinding. So, the client-side filtering might be applied through the use of swing TableRowSorter and RowFilter. Am I right ? if so, you could use the method
int row = myTable.convertRowIndexToModel(myTable.getSelectedRow());
to convert the selected row in the filtered view to the actual selected row in the model.
For the second question (bean to keep the selected item of table)
You could also create a binding using this as the source/target object, and create a property selectedElement in the class containing the table. Thus, you won't need another class. The code will be : createAutoBinding(UpdateStrategy.READ_WRITE, myTable,
ELProperty.create("${selectedElement}"), this, BeanProperty.create("selectedElement"), "selectedElementBinding");
(note also that READ_WRITE binding is not really used, as beans binding does not support changing the selected element from the bound property)
I need to generate encoding String for each item I inserted into the database. for example:
x00001 for the first item
x00002 for the sencond item
x00003 for the third item
The way I chose to do this is counting the rows. Before I insert the third item, I count against the database, I know there're already 2 rows, so the next encoding is ended with 3.
But there is a problem. If I delete the second item, the forth item will not be the x00004,but x00003.
I can add additional columns to table, to store the next encoding, I don't know if there's other better solutions ?
Most databases support some sort of auto incrementing identity field. This field is normally also setup to be unique, so duplicate ids do not occur.
Consult your database documentation to see how it is done in your database and use that - don't reinvent the wheel when you have a good mechanism in place already.
What you want is SELECT MAX(id) or SELECT MAX(some_function(id)) inside the transaction.
As suggested in Oded's answer a lot of databases have their own methods of providing sequences which are more efficient and depending on the DBMS might support non numeric ids.
Also you could have id broken down into Y and 00001 as separate columns and having both columns make up primary key; then most databases would be able to provide the sequence.
However this leads to the question if your primary key should have a meaning or not; Y suggest that there is some meaning in the part of the key (otherwise you would be content with a plain integer id).