Displaying contents of an object in the query result - java

I have the following code in java:
try {
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
Query userQuery=session.createQuery("select u.userId, u.username,p.profileContent from User as u inner join u.profiles as p");//, p.profileContent
List userList=userQuery.list();
for(int i=0;i<userList.size();i++){
System.out.println(userList.get(i));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.flush();
session.close();
}
I am trying to display the result of the query but only the object is displayed. Can you suggest me the way to display the contents of the objects. Currently i am getting result like:
[Ljava.lang.Object;#64bef361

for (Object o : userList) {
Object[] row = (Object[]) o;
System.out.println(Arrays.toString(row));
}
But you should probably use a debugger instead of cluttering your code with such loops.

whenever you try to print any object reference, it's toString() method is called. Now, suppose your userList is of type User. You have not overridden toString() method in your User class. So, what's happening currently is toString() method of object class is called.The Object class has implemented this method in such a way that it prints it's fully qualified package name and it's hashcode.
So, simply override this toString() method in your User class and it will start printing entire data as you have configured in this method. You can manually override this method, or if you have an IDE line netbeans or eclipse, just right click anywhere in the java file and select generate ToString method.

In Java, good programming practice is to override Object.toString() So that you avoid this problem. If you want more meaningful output then what you are getting, then adhere to the standards that are encouraged by the API.refer to the documentation when in doubt

I figured out the problem. I did not know the result of the query joining more than one tables will store the result as array of Objects class.
Query userQuery=session.createQuery("select u.userId, u.username,p.profileContent from User as u inner join u.profiles as p");//, p.profileContent
Iterator ite = userQuery.list().iterator();
while ( ite.hasNext() ) {
Object[] pair = (Object[]) ite.next();
Integer user = (Integer) pair[0];
String userName=(String) pair[1];
String profileContent=(String) pair[2];
System.out.println(user+" "+userName+" "+profileContent);
}

Related

Trying to write a method in Java that will search a database list and return a Customer object, given a customerID

I am creating a customer manager application for a Java course. I have it separated as per the requirements into 3 packages. The first package has a class called Customer, which models a customer and it's instance variables, such as customerID. The second package is a customer database that includes an ArrayList. The third package is going to be a menu driven UI that will allow the user to choose between 4 options. Currently, I am stuck trying to write a method that will search through the list for a given customerID and return a Customer object.
In the customer database class, I am getting the customerID from the user within the method. Then, I am running a for loop that should traverse the method to see if the customerID is found. I am having issues on how to return a customer object if the id is a match.
public Customer searchCustomer(String customerID) {
System.out.println("Enter customer ID you want to find:");
customerID = scnr.next();
Customer c;
for (int i = 0, i < customerList.size(); i++ {
c = customerList.get(i);
if (customerList.get(i).equals(customerID) {
String foundID = customerID;
}
}
}
I want to return Customer c at the end of the method, but cannot figure out how to do this.
In the if statement one can just write return c. This will return the first Customer that matches. At the end of the method one can return null or throw an exception if the Customer wasn’t found.
You compare Customer object with CustomerId.
Change code to
if (customerList.get(i).getId().equals(customerID) {
return customerList.get(i);
}
A few of the potential mistakes you're making are:
Passing in an parameter to your method that you're not using. Either do the Scanner stuff outside of the method and then pass the ID to the method, or do the Scanner part in the method and have no parameters. The former approach is generally the preferred one, though.
Comparing the customer to a String. You need to compare the user-entered ID to the Customer object's ID field. The String the user enters will never be equal to the entire Customer object.
You're not returning anything from the method. Once you find the Customer you're looking for, you need a return statement.
Also, you can use Java's "enhanced for loop" to make the code a bit cleaner. Here's some code that assumes that your Customer objects use a String as their ID, and have a .getID() method on them to get their ID.
Here's some code that needs to search for a customer. This can be in another method.
System.out.println("Enter customer ID you want to find: ");
customerID = scnr.next();
Customer customer = searchCustomer(customerID);
And here's the search method that loops through the customerList
public Customer searchCustomer(String customerID) {
for(Customer customer : customerList) {
if (customer.getId().equals(customerID) ) {
return customer;
}
}
return null; // Or perhaps throw an exception.
}
Note that I'm making a lot of assumptions about how the other parts of your code that I haven't seen are structured, so you very probably will have to modify this code sample if you want to use it, but hopefully it puts you on the right track.

Java : What is the best way to check variable type in runtime?

I want to know the best way to check variable type at runtime.
public Iterator<?> read(String entityName, String propertyName, Object propertyValue) {
String query = "select * from " + entityName + " where " + propertyName + "=";
try {
int value = Integer.parseInt((String)propertyValue);
query=query+value;
} catch (NumberFormatException e) {
// failed
}
try {
String value = (String)propertyValue;
query=query+"'"+value+"'";
} catch (ClassCastException e) {
// failed
}
try {
float value = Float.parseFloat((String)propertyValue);
query=query+value;
} catch (NumberFormatException e) {
// failed
}
//Creating JDBC connection and execute query
Iterator<Element> result=queryConn.execute();
return result;
}
I need to check the variable type is int, float or String during runtime. Is there any other best way to do this?
Or Do I need to write seperate method for each variable type?
try this code :
if(floatVariable instanceof Float){}
if(intVariable instanceof Integer){}
if(stringVariable instanceof String){}
There are many ways to handle this scenario.
Use function overloading for different data types
Use instanceof operator to determine data type
Try to cast property value in any numeric data type, if successfully castes then ignore single quotes otherwise apply single quotes
since you are getting object as input you can always check using instanceof keyword.And instead of using primitives try using classes like(Integer.class).And one more thing is you should use PreparedStatement always.Your code is prone to SqlInjection.
Is there any other best way to do this?
I would recommend that you name the columns you want to select in your actual query. If you take this approach, you can parse each column as the appropriate type without worrying about type casting issues. If, for example, the first column selected were an integer type, then you would just call Integer.parseInt() without worrying about having the wrong type.
And here is an argument why using SELECT * is an anti-pattern:
If you use SELECT * as your query, then we don't even know how many columns are being returned. To even take a guess at that, we would have to analyze how many columns your code seems to expect. But, what would happen if someone were to change the schema, thereby possibly changing the order in which the RDBMS returns columns? Then your entire application logic might have to change.

json output is not in sorting order

I have created web service in JAVA Netbeans and called MySQL data through rest web service.
Edited code:
For loop shows all areas in sorting order then why as json output all data are not displayed in ascending order???
my method is as follows :
#GET
#Path("/ShowAreasDup")
#Produces(MediaType.APPLICATION_JSON)
public List<EntityAreas> ShowAreasDup(){
ArrayList<EntityAreas> listSort;
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASSWORD);
String query = "SELECT * FROM Areas ORDER BY AreaName";
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery(query);
// iterate through the java resultset
while (resultset.next())
{
int id = resultset.getInt("AreaID");
String restroName = resultset.getString("AreaName");
EntityAreas anames=new EntityAreas();
anames.setAreaid(id);
anames.setAreaname(restroName);
ShowentityAreas.put(id, anames);
}
statement.close();
}
catch(HeadlessException | SQLException |ClassNotFoundException ee)
{
JOptionPane.showMessageDialog(null, ee);
}
listSort=new ArrayList<EntityAreas>(ShowentityAreas.values());
Collections.sort(listSort,new Comparator<EntityAreas>(){
#Override
public int compare(EntityAreas o1, EntityAreas o2) {
return o1.getAreaname().compareTo(o2.getAreaname());
}
});
for(EntityAreas entityarea:listSort){
System.out.println(entityarea);
}
return listSort;
}
thank you in advance for help
Edit :
Above code is works perfectly for me
thanks to all for giving me a direction to the answser :)
Given your code, there could be some hypothesis. The most probable is that ShowAreas stores the information in an non ordered data structure (for example an HashMap).
If you want to maintain your values in order , you have to use some additional data structure. For example, you can use a TreeSet for the values.
Another solution could be to sort the values immediatly before returning them (javadoc),
// Get the elements
List<Areas> areas = new ArrayList<Areas>(ShowAreas.values());
// Sort them
Collections.sort(areas);
// Return them
return areas;
Pay attention: if you want to use this method, the class Areas must implement Comparable.
A last advise: don't put the code that interacts with the database in the class that has the responsibility to receive external REST calls. You violates the single responsibility principle and your application will become unmaintainable very quickly. Try to use a structure Controller - Service - Repository.

Retrieving multiple values from an arraylist

I have saved values retrieved from a database in java to an arraylist.
I have used a class to save the data to the array list as shown below.
ArrayList<NewSms> details = new ArrayList<NewSms>();
try{
Statement query = conn.createStatement();
ResultSet result = query.executeQuery("Select `senderAddress,message,linkid from sdp_smsincoming where status=0 AND smsServiceActivationNumber =1234 ");`
while(result.next()){
String address = result.getString("senderAddress");
String message = result.getString("message");
String linkid = result.getString("linkid");
NewSms smsdetails = new NewSms();
smsdetails.set_address(address);
smsdetails.set_message(message);
smsdetails.set_linkid(linkid);
details.add(smsdetails);;
}
}
However i now want to retrieve the values individually per row,from another class in the program.How can i do this?By individually i mean getting the address,message and linkid per row in the arraylist.
However i now want to retrieve the values individually per row,from another class in the program.How can i do this?
You just access each NewSms in the list. To access one by index, you could use:
NewSms sms = details.get(2); // Or whatever
// Now access the properties of sms
Or to access each of them in turn, use an enhanced for loop:
for (NewSms sms : details) {
// Now access the properties of sms
}
Note that to comply with Java naming conventions, your NewSms class should have methods such as getAddress, setAddress - not set_address.
Also note that you need to close your result set / statement / connection - if you're using Java 7, you can use a try-with-resources statement; otherwise you should use finally blocks.
EDIT: If your problem is actually just returning the list, that's easy:
public List<NewSms> loadSmsDetails() {
// Code as before...
return details;
}
Then just call it from your other class:
// Where repository is a reference to an instance of the class containing the above method
List<NewSms> allDetails = repository.loadSmsDetails();
for(NewSms smsdetails:details){
String address = smsdetails.get_address();
String message = smsdetails.get_message();
String linkId = smsdetails.get_linkid();
}
However i now want to retrieve the values individually per row,from
another class in the program
You need to pass the arraylist to the another class and iterate over it there to get the individual elements. The idea is to use a common araylist - to store the values from the resultset and in another class to iterate through them.

how to display the information inside an object

we are assigned to implement the inside of a code block wherein it is associated with a given class (EmployeeProjectDetail) which is declared as a arraylist.
my code follows below.
public List<EmployeeProjectDetail> getEmployeeProjectHistory(long employeeID, long projectID) {
List<EmployeeProjectDetail> detailList = new ArrayList<EmployeeProjectDetail>();
return detailList;
}
I tried inputting the statements.
detailList.contains(projectDAO.getEmployeeProjects(employeeID));
detailList.contains(projectDAO.getEmployeeProjectRoles(employeeID, projectID));
the code then doesn't return any value but the invovled sql queries in projectDAO class are thoroughly handled. any help will be appreciated.
contains checks whether an item is in a list what your are looking for is add.
You should add the line
detailList.add(projectDAO.getEmployeeProjects(employeeID));
Update (I'm guessing on the method and class names)
Based on the ClassCastException it appears that getEmployeeProjects(employeeID) returns an ArrayList. If the objects in this ArrayList are EmployeeProjectDetail's you can just replace the method body with return projectDAO.getEmployeeProjects(employeeID);. If they are a different object representing a project, say EmployeeProject, you would need to replace the method body with the following code:
List<Project> projects = projectDAO.getEmployeeProjects(employeeID);
ArrayList<EmployeeProjectDetail> projectDetails = new ArrayList<EmployeeProjectDetail>();
for (Project project : projects) {
if(project.getProjectID == projectID){
projectDetails.add(project.getProjectDetail());
}
}

Categories