Return an int value to Database - java

I am working on an application which makes it easier for employees to return lost luggage.
I'm working on a screen which registers a piece of luggage.
The status ComboBox is filled with data from the database, as well as the CustomerID combobox.
SCREEN:
http://gyazo.com/d81c7c2377c79eb2b42d6f101fb8d5f5
Now the ComboBox fetches an SQL query, and shows a firstname. But the customer has a customerID as well. For now i have a method which sets the value of the variable customerId, with:
lug.setCustomerID(String.valueOf(CustomerID.getSelectedItem()));
But then it sets its value to 'Khoa'.
How can i show a name in my combobox, but get the INT value of the customerID?

Instead of just adding strings to the ComboBox you can add an object with both ID and String.
You need to override the toString() function of your class from which you create the customer object.
public class Customer {
private String name;
private int id;
public Customer(String label, int identifier) {
name = label;
id = identifier;
}
public getId() { return id; }
#Overrider public String toString() { return name; }
}
You can when using an object out of that class
lug.setCustomerID(CustomerID.getSelectedItem().getId());

You should wrap your data in simple bean (e.g. Customer) with 2 fields: int id; String firstName and toString must return firstName.
After declare your combobox as JComboBox<Customer>.
The result will look like lug.setCustomerID(CustomerID.getSelectedItem().getId());

Related

How to pass a String parameter to a function from a set of allowed values

I'm making my own Java class called SelectRequestBuilder in order to easily create SQL requests. There a function addColumnToSelect which must take the column name as a parameter. The issue is that I want to make sure that the column name specified by the user is in the table where he want to select informations from.
So I thought that the type of the parameter column_name should be an enum like so :
public enum USER_COLUMN {
ID("id"),
USERNAME("username"),
PASSWORD("password"),
private final String name;
USER_COLUMN(String name) {this.name = name;}
#Override
public String toString() {
return name;
}
}
Then, in my function I could get the column name and I would be sure that the column name passed as a parameter is a valid one.
Yet, I got stuck when I wanted to be able to extend this class to not only the users table but to every table. What I mean is that my SelectRequestBuilder must be able to select values from an other table genders for example.
The reason why it's giving troubles is that my function can no longer take a parameter column_name of type USER_COLUMN because it's only for the users table.
Finally, my solution would be something like so:
private void addColumnToSelect(USER_COLUMN col) {
addColumnToSelect(col.toString());
}
private void addColumnToSelect(GENDER_COLUMN col) {
addColumnToSelect(col.toString());
}
private void addColumnToSelect(ROLE_COLUMN col) { // Role is an other table
addColumnToSelect(col.toString());
}
private void addColumnToSelect(String col_name) {...}
But this solution is not satisfying in the sense that I must create an other function for every table in the database. This is why I ask you this question, I want your help to find a more satisfying solution ! :)
Enums can implement interfaces, you can use that to your advantage:
interface DatabaseColumn {
String columnName();
}
enum UserColumns implements DatabaseColumn {
ID("id"),
USERNAME("username"),
PASSWORD("password");
private final String name;
UserColumns(String name) {
this.name = name;
}
#Override public String columnName() {
return name;
}
}
Then other enums could implement the same interface, and your signature would become
private void addColumnToSelect(DatabaseColumn col) {
}

Integer property as automated generated number

I'm creating a simple Java app that would store and display information for customers.
I want to make the id as an automated generated number but having problems with that, don't know should I set it in get or set methods?
Can anyone help me to use that value as?
Here is an example:
public class Customer{
public Person(String firstName, String lastName, String email, String address, String country){
this.id.set(Integer.parseInt(UUID.randomUUID().toString()));
this.firstName.set(firstName);
this.lastName.set(lastName);
this.email.set(email);
this.address.set(address);
this.country.set(country);
}
private final IntegerProperty id = new SimpleIntegerProperty(this,"Id",0);
private final StringProperty firstName = new SimpleStringProperty(this,"First Name","");
private final StringProperty lastName = new SimpleStringProperty(this,"Last Name","");
private final StringProperty email = new SimpleStringProperty(this,"E-mail","");
private final StringProperty address = new SimpleStringProperty(this,"Address","");
private final StringProperty country = new SimpleStringProperty(this,"Country","");
I also created generic bean methods but it's just simple like this:
public StringProperty firstNamePropery(){
return firstName;
}
public String getFirstName(){
return firstName.get();
}
public void setFirstName(String firstName){
this.firstName.set(firstName);
}
//...rest of the methods...
I tried to use this but doesn't work:
public IntegerProperty idProperty(){
return id;
}
public Integer getId(){
return id.get();
}
public void setId(){
this.id.set(Integer.parseInt(UUID.randomUUID().toString()));
}
Thank you for helping me on this one.
A UUID string looks like this 38400000-8cf0-11bd-b23e-10b96e4ef00d. You can't parse this string into an Integer.
If you want to use UUIDs as the Ids for the customers then, declare the attribute as UUID or String instead of Integer.
EDIT I
Also, I don't need to store it as an Integer value, the string can do
job but just can't get to create that number when creating a new
instance of that class.
To use a UUID as a String:
In the Customer class the id attribute must be of type String instead of Integer (or int).
To get a new String representation of the UUID you call UUID.randomUUID().toString(). The result of this call can be assigned to the customer's id without doing any parsing.
Also note that the signatures of the getter and setter have to change accordingly.
In the current setId() method you are creating a new id. This would override the id assigned when the Customer is created using the call in the constructor. If you want flexibility to assign a new id you can have the setId receive a new UUID string and assign that as a new id to the Customer object.
public class Customer{
public Customer(String firstName, String lastName, String email, String address, String country){
this.id.set(UUID.randomUUID().toString());
}
...
public String getId(){
return this.id;
}
public void setId(String newId){
this.id = newId;
}
}
Note: The class name is Customer and the constructor is Person. This is wrong, both must have the same name. You must have some compiler error telling you this. I will assume the correct name of the class and constructor is Customer
/EDIT I
The use case for UUID is when you need to have a unique id without checking if the id already exists with some other party (for example a database engine or a server in a network application without a central server).
If what you want to use is Integer (or Long) there is no real reason to use a Random number, you can use a sequential number for your ids.
If if is a standalone application in javafx, and you are not using different threads to create customers in parallel, then there isn't much more to worry about.
On the other side if it is a client server application. Then you have take in mind the concurrent access of clients to the server.
If you delegate the id creation as a sequence in the database then, the concurrency issue or generating duplication in the id is taken care by the database itself. This could be an autoincrement field in the same customer table (assuming you are using one), a sequence, or a table acting as a sequence. On another side, if it is a class of yours which is going to generate the ids one by one, then you will have to take care of concurrent requests. You will have to make sure that only one thread can increment the id at a time.
Regarding getters and setters, getXxx() returns the value of xxx attribute. and setXxx(123) would set or assign the value 123 to the attribute xxx;

How can I put a index in a jcombobox in java?

I want to put in a jcombobox, the name and use the id for link the option select and the name.
I get the data of the db, but I don't know the way for add a items.
I try to write a item, with 2 parameters, but in the combobox appear the class name, not the value :
This is my code
rs = (ResultSet) stmt.executeQuery();
while ( rs.next() ) {
cbHabitaciones.addItem(new Item(rs.getInt("id"), rs.getString("tipo") +" - " +rs.getString("precio")));
}
Easiest way for you would be to override toString() method of the class which instances you are putting in the JCombo's model. That way you get your 'nice name' for each item. That class, of course, should contain everything you need for each item, e.g. id and name. On selection change, you can than use the id of the selected item.
If you cannot override 'toString()' or you want to separate objects you already have (e.g. if they are DTO) from the presentation objects, create your own class with only the things you need.
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String toString() {
return this.getName();
}
}

Get selected value JList or List in Java Swing, stuck with getElementAt() of ListModel

i am using Swing List control to bind data, I (must) use a class to make the model
public class SubjectListModel extends AbstractListModel<String> {
public ArrayList<Subject> listSubjects;
public SubjectListModel(ArrayList<Subject> listSubjects) {
this.listSubjects = listSubjects;
}
#Override
public int getSize() {
return listSubjects.size();
}
#Override
public String getElementAt(int index) {
return listSubjects.get(index).name;
}
class Subject{
int id;
string name;
}
I wish to use the List to bind my ArrayList, Can I set something like "display text field" for "name" field, and "value field" for my "id"? So that I can retrieve those values as needed.
The best dream is I can retrieve whole the selected "Subject" instead of a string field.
I seen the list only have getSelectedValue, and if I want to display the subject in the List, I must set getValueAt() in model to return the "name", and getSelectedValue() return the selected "name" too :( If I change getElementAt() in model class to return "Subject", the list will display #object.abxdef
Just override toString() of Subject, and return what ever you want to be displayed in the list. Then add all your Subject instances to the list. No need for a custom ListModel. Just use a DefaultListModel. When you get the selected Subject just use one of it's getters to the field you want.
Also no need to store your object in two locations, (i.e. the ListModel and the ArrayList) just add everything to the model.
class Subject {
private int id;
private String name;
public Subject(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public String getName() { return name; }
#Override
public String toString() {
return name;
}
}
DefaultListModel model = new DefaultListModel();
model.addElement(new Subject(1, "Math"));
Subject subject = (Subject)model.getElementAt(0);
System.out.println(subject);
// result -> Math

Wondering if I'm doing this immutability exercise correctly

My professor just went over mutable and immutable, and gave us this coding exercise to complete.
1) Create a Customer object called customer with initial values of 1 and "Cust1"
respectively.
2) Display the customer object to the screen using the toString() method.
3) Create a String object reference called name and assign to it the customer's name.
4) Assign the value "Bo Beep" to the object reference name.
5) Display the customer object to the screen using the toString() method.
The output should look like this.
Customer{id=1, name=Cust1}
Customer{id=1, name=Cust1}
I currently have 2 seperate classes, here they are. I'm not sure whether I'm doing it correctly, I think I have done the first 2 right, but I'm not sure about 3-5.
Any input is helpful, thanks!
Here's my main class,
package hw01;
public class Main {
static Customer customer = new Customer(1, "cust1");
static Customer name = new Customer(1, "Bo Peep");
public static void main(String[] args) {
System.out.println(customer);
System.out.print(customer);
}
}
And here's my Customer class.
package hw01;
public class Customer {
private int id;
private String name;
public Customer() {
}
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + '}';
}
}
Sounds like for #3 it should be something like this:
String name = customer.getName();
and then #4 would be:
name = "Bo Peep";
The goal of the exercise I think is to demonstrate that even though name and customer.name reference the same String object, since a String is immutable when you set name = "Bo Peep"; you're not changing the actual String object but instead creating and referencing a new String object. If the String were mutable then printing the customer the 2nd time would display the name "Bo Peep".

Categories