Get image from mysql database using javafx - java

I am trying to retrieve images from mysql database using javafx. Images are stored in database using long blob. garbage values appear when doing so . this is the code used to retrieve image from database.
JFXTreeTableColumn<Property,String> propertyImage = new JFXTreeTableColumn<>("Image");
propertyImage.setPrefWidth(100);
propertyImage.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Property, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Property, String> param) {
return param.getValue().getValue().propertyImage;
}
});
the property view
Database connection
public class Property extends RecursiveTreeObject<Property>{
StringProperty propertyId;
StringProperty address;
StringProperty state;
StringProperty zipCode;
StringProperty price;
StringProperty bedNum;
StringProperty bathNum;
StringProperty propertyImage;
StringProperty propertyType;
StringProperty propertyStatus;
StringProperty squareFeet;
StringProperty parkingSpot;
StringProperty agent_id;
public Property(){
super();
}
public Property(String propertyId, String address, String state, String zipCode, String price, String bedNum, String bathNum, String propertyImage, String propertyType, String propertyStatus, String squareFeet, String parkingSpot, String agent_id) {
this.propertyId = new SimpleStringProperty(propertyId);
this.address = new SimpleStringProperty(address);
this.state = new SimpleStringProperty(state);
this.zipCode = new SimpleStringProperty(zipCode);
this.price = new SimpleStringProperty(price);
this.bedNum = new SimpleStringProperty(bedNum);
this.bathNum = new SimpleStringProperty(bathNum);
this.propertyImage = new SimpleStringProperty(propertyImage);
this.propertyType = new SimpleStringProperty(propertyType);
this.propertyStatus = new SimpleStringProperty(propertyStatus);
this.squareFeet = new SimpleStringProperty(squareFeet);
this.parkingSpot = new SimpleStringProperty(parkingSpot);
this.agent_id = new SimpleStringProperty(agent_id);
}
}
DB connection
ObservableList<Property> properties = FXCollections.observableArrayList();
Connection connection = DBConnection.getConnection();
try {
PreparedStatement ps = (PreparedStatement)connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
properties.add(new Property(rs.getInt(1)+"",rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11),rs.getString(12),rs.getString(13)));
}
} catch (SQLException ex) {
Logger.getLogger(SearchSalePropertyController.class.getName()).log(Level.SEVERE, null, ex);
}

Finally, you posted the codes for database access. You are already doing it wrong when you were getting the data from the ResultSet.
while(rs.next()) {
InputStream in = new rs.getBinaryStream(8);
Image image = getImageFromStream(in); // You need to convert this back into a JavaFX Image instance,
// which depends on the original Image, e.g. file format etc.
// It could be as simply as new Image(in) using the JavaFX Image constructor
properties.add(new Property(
rs.getInt(1) + "",
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getString(7),
image,
rs.getString(9),
rs.getString(10),
rs.getString(11),
rs.getString(12),
rs.getString(13)
));
}
Of course, Property.propertyImage should also be changed to ObjectProperty<Image>. Similarly the column should also be changed to JFXTreeTableColumn<Property, Image>.

Related

How to load the data to tableview from database using javafx

i am beginner of javafx. i just use way java jtable like load the data but i couldn't load the data to tableview what i tried so far i attached below.how to load the data to tableview
#FXML
private TableColumn<?, ?> table1;
public void table_load()
{
int c;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/addressbook", "root","");
pst = con.prepareStatement("select * from records");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rd = rs.getMetaData();
c = rd.getColumnCount();
df = (DefaultTableModel)table1.getCellData(0);
df.setRowCount(0);
while (rs.next())
{
Vector v = new Vector();
for (int i=1; i<=c; i++)
{
v.add(rs.getString("id"));
v.add(rs.getString("name"));
v.add(rs.getString("address"));
v.add(rs.getString("phone"));
}
df.addRow(v);
}
} catch (SQLException ex) {
} catch (ClassNotFoundException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
Usually you don't add the data to a TableColumn directly. The usual way would be to have objects of a type you can add. Let's assume your result set would contain objects of type Customer and you could extract one or many customer objects from your result set. Then you would rather work with the following (need to be defined in the fxml file:
A superordinate table like TableView <Customer> customerView
a number of table columns like:
TableColumn<Customer, String> idColumn
TableColumn<Customer, String> nameColumn
TableColumn<Customer, String> addressColumn
TableColumn<Customer, String> phoneColumn
You need to set the value factory for the columns to make clear which attribute is to be displayed.
idColumn.setCellValueFactory(new PropertyValueFactory<>("[ATTRIBUTE NAME IN CUSTOMER CLASS]"));
like
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
The last step should be to fill the table view with data:
customerView.setItems(observableCustomers);
where observableCustomers is a list of type ObservableList<Customer>. javafx.collections.FXCollections will help you here to create a corresponding object.
It should be similar to this:
#FXML
TableView <Customer> customerView;
#FXML
TableColumn<Customer, String> idColumn;
#FXML
TableColumn<Customer, String> nameColumn;
#FXML
TableColumn<Customer, String> addressColumn;
#FXML
TableColumn<Customer, String> phoneColumn;
ObservableList<Customer> observableCustomers;
// init method or constructor, whatever suits your needs
private void initTable() {
observableCustomers = FXCollections.observableArrayList();
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
addressColumn.setCellValueFactory(new PropertyValueFactory<>("address"));
phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));
}
public void table_load()
{
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/addressbook", "root","");
pst = con.prepareStatement("select * from records");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rd = rs.getMetaData();
// CAST/TRANSFORMATION TO BE DONE BY YOU
List<Customer> customerList = ((List<Customer>) rs.toList());
// only if necessary
observableCustomers.clear();
// add customers
observableCustomers.addAll(customerList);
} catch (SQLException ex) {
} catch (ClassNotFoundException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
Unlike in Swing, a JavaFX TableView does not use a separate model. Instead, the data is the model. You pass this data to the TableView using the TableView’s setItems method.
This means you need to create a class to hold your data. Since your table is called records, I would name the data class Record.
If you look at the documentation of JavaFX classes, you should notice a pattern. Bean properties are encapsulated attributes, which consist of three methods:
A read method, which always starts with get followed by a capital letter.¹
A write method, which always starts with set followed by a capital letter.²
A property method, whose name always ends with Property.
For instance, consider the javafx.stage.Window class. It has an “opacity” property, which is represented by these methods:
double getOpacity()
void setOpacity(double)
DoubleProperty opacityProperty()
Your data class needs to follow the same pattern:
public class Record {
private final StringProperty id;
private final StringProperty name;
private final StringProperty address;
private final StringProperty phone;
public Record() {
id = new SimpleStringProperty(this, "id");
name = new SimpleStringProperty(this, "name");
address = new SimpleStringProperty(this, "address");
phone = new SimpleStringProperty(this, "phone");
}
public StringProperty idProperty() { return id; }
public String getId() { return id.get(); }
public void setId(String newId) { id.set(newId); }
public StringProperty nameProperty() { return name; }
public String getName() { return name.get(); }
public void setName(String newName) { name.set(newName); }
public StringProperty addressProperty() { return address; }
public String getAddress() { return address.get(); }
public void setAddress(String newAddress) { address.set(newAddress); }
public StringProperty phoneProperty() { return phone; }
public String getPhone() { return phone.get(); }
public void setPhone(String newPhone) { phone.set(newPhone); }
#Override
public String toString() {
return String.format("%s[id=%s, name=%s]",
getClass().getName(), getId(), getName());
}
}
Creating these objects is straightforward:
#FXML
private TableView<Record> table;
#FXML
private TableColumn<Record, String> idColumn;
#FXML
private TableColumn<Record, String> nameColumn;
#FXML
private TableColumn<Record, String> addressColumn;
#FXML
private TableColumn<Record, String> phoneColumn;
// ...
ObservableList<Record> records = FXCollections.observableArrayList();
try (ResultSet rs = pst.executeQuery()) {
while (rs.next())
{
Record record = new Record();
record.setId(rs.getString("id"));
record.setName(rs.getString("name"));
record.setAddress(rs.getString("address"));
record.setPhone(rs.getString("phone"));
records.add(record);
}
}
table.setItems(records);
Instead of a table model, you must instead tell each table column which data it should display:
idColumn.setCellValueFactory(f -> f.getValue().idProperty());
nameColumn.setCellValueFactory(f -> f.getValue().nameProperty());
addressColumn.setCellValueFactory(f -> f.getValue().addressProperty());
phoneColumn.setCellValueFactory(f -> f.getValue().phoneProperty());
¹ Read methods whose return type is primitive boolean may use is instead of get.
² Write methods are not needed for read-only properties.

Spring/JPA #OneToMany relationship returns a list of size 0, when it should return more. Why?

I am using spring/jpa for a project, and I have an entity which has an #OneToMany annotation on a List.The other entity has an #ManyToOne annotation. Although when I retrieve the parent entity by its id, the size of the returned List (child entity) is always 0
Text version of test
#Test
public void createReccomendation() throws ServiceException, FileNotFoundException, UserDoesNotExistException, UserNameIsNotUniqueException, IllegalUserNameException {
String uid = UUID.randomUUID().toString();
Employee employee = employeeService.createEmployee("hi", uid+"#me.com", uid, "secret password", 23.234, 23.23, "image", "23dAD", "seattle", "usa");
List<String> images = new ArrayList<>();
String image1 = "image1/url";
String image2 = "image2/url";
String image3 = "image3/url";
images.add(image1);
images.add(image2);
images.add(image3);
Employee e = employeeService.getEmployeeById(employee.getId());
Recommendation rec = recommendationService.createRecommendation(e.getId(), "title", "Description", 23.23, 23.23, "persikogatan", "stockholm", "Sweden", images);
Recommendation rec2 = recommendationService.getRecommendationById(rec.getId());
Assert.assertEquals(rec.getTitle(), "title");
Assert.assertEquals(rec.getRecommendationimages().get(0).getPath(), image1);
Assert.assertEquals(3, rec2.getRecommendationimages().size());
}
This parent entity
#Entity
#Table(name = "recommendation")
public class Recommendation extends BusinessEntity {
#ManyToOne
#JoinColumn(name = "employeeid")
private Employee employee;
#OneToMany(mappedBy = "recommendation", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
List<RecommendationImage> recommendationimages;
public Recommendation() {}
public Recommendation(Employee employee, String title, String description, double targetLat, double targetLong,
String street, String city, String country, List<RecommendationImage> images
) {
this.employee = employee;
this.title = title;
this.description = description;
this.targetLat = targetLat;
this.targetLong = targetLong;
this.street = street;
this.city = city;
this.country = country;
this.active = true;
this.recommendationimages = images;
}
And this child entity
#Entity
#Table(name = "recommendationimage")
public class RecommendationImage extends ImageEntity{
#ManyToOne
private Recommendation recommendation;
Super class of child entity
#MappedSuperclass
public abstract class ImageEntity extends BaseEntity{
#Column(name="path", length=700)
String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
RecommendationService class
#Service
public class RecommendationService{
private static final Logger log = LogManager.getLogger(DealService.class);
#Autowired
RecommendationRepository recommendationRepository;
public Recommendation getRecommendationById(Long id){
return recommendationRepository.findOne(id);
}
}
public List<RecommendationImage> translateToRecommendationImages(List<String> rawImages) throws ServiceException {
try{
List<RecommendationImage> recommendationImages = new ArrayList<>();
for(String image: rawImages){
RecommendationImage newImage = new RecommendationImage(image);
recommendationImages.add(newImage);
}
return recommendationImages;
}catch(Exception e){
log.warn("** SERVICE EXCEPTION ** FOR METHOD: translateRecommendationImages()");
throw new ServiceException("Could not translate raw images to RecommendationImage", e);
}
}
public Recommendation createRecommendation(Long employeeId, String title, String description, double targetLat,
double targetLong, String street, String city, String country,
List<String> rawImages) throws ServiceException {
log.info("createRecommendation(): employeeId: "+employeeId+" recommendationTitle: "+title);
Employee employee=null;
Recommendation rec=null;
String imagepath=null;
try {
List<RecommendationImage> images = translateToRecommendationImages(rawImages);
employee = employeeRepository.getEmployeeByid(employeeId);
rec = new Recommendation(employee, title, description, targetLat, targetLong, street, city, country, images);
// Recommendation rec2 = CheckProximity.getRecommendationProximity(rec, employee);
return recommendationRepository.save(rec);
}catch(Exception e){
log.warn("** SERVICE EXCEPTION ** FOR METHOD: createRecommendation(): employeeId: "+employeeId);
e.printStackTrace();
throw new ServiceException("Could not create recommendation at this time: "+rec.toString(), e);
}
}
Any help would be appreciated thanks!
Nowhere in your supplied code to you actually populate the list of RecommendationImages. So I'm going to guess.
When dealing with bidirectional relationships, in order for them to be persisted, the side of the relationship without the mappedBy needs to be updated. I'm guessing that you add RecommendationImages to your Recommendation, without setting the Recommendation of your RecommendationImages.
Typically, you would need a method like this:
public class Recommendation {
//...
private List<RecommendationImage> images = new ArrayList<>();
public void addRecommendationImage(final RecommendationImage newImage) {
recommendationImages.add(newImage);
newImage.setRecommendation(this);
}
}
Update: With the new code supplied it seems my guess was correct. Make the changes above, and then change the for-loop in translateToRecommendationImages to this:
public List<RecommendationImage> translateToRecommendationImages(Recommendation recommendation, List<String> rawImages) throws ServiceException {
//try and whatnot
for(String image: rawImages){
recommendation.addRecommendationImage(new RecommendationImage(image));
}

Java - String NullPointerException

I'm making a mysql database connector with java to show all the data.
When I run the code, I get an NullPointerException in my getData() function.
here is my code.
public String[][] getData() {
String values[][];
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values[i][0] = id;
values[i][1] = name;
values[i][2] = adress;
values[i][3] = catagory;
i++;
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
When the value of the String values is nothing I get The error. But if I give the String allready a value it says nothing .
public String[][] getData() {
String values[][] = {{"","","",""},
{"","","",""},
{"","","",""},};
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values[i][0] = id;
values[i][1] = name;
values[i][2] = adress;
values[i][3] = catagory;
i++;
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
I want more data than that in my data String. how can I let it automatically do that??
Tnx.
PS.
The function is called in my class FrameGUI and has to change to Object
public class FrameGUI extends JFrame {
public JTable dataHolder;
Mysql mysql = new Mysql();
public String[] columnNames = {
"ID", "Name", "Adress", "Catagory"
};
-> public Object[][] data = mysql.getData();
public FrameGUI() {
init();
mysql.getData();
}
}
You do not initialize String values[][] so it is null. You either need to initialize it first or use a more appropriate datastructure like a List.
You should define a class and use a List (e.g. the ArrayList) instead.
e.g. if you want to call it User -
public class User {
private String id;
private String name;
//...
}
and a list
List<User> users = new ArrayList<User>();
and then instantiate the User class for each row and add the new instance to the list -
User currUser = new User();
users.add(currUser);
//set values from result set
The list can grow automatically when needed and the code is much more readable than using the array.
You get an index out of bounds in the first example because a String[][] (or String Matrix) gets initialized as a zero-length array.
In the second instance, you initialized the array to a size of 3x4 - that works so long as you only get 3 results back.
What you really need is a data structure with a dynamic size. Arrays aren't automatically sized dynamically. Try using a collection implementation like ArrayList or LinkedList or Vector.
Also, instead of saving your values to a String[], try creating a bean class that can hold your result. Create a new instance of it for each result that you get back instead of initializing a new array.
Because you didn't initialized your array, that is why you get NPE. Actually I suggest you to use List for your purposes:
public ArrayList<ArrayList<String>> getData() {
ArrayList<ArrayList<String>> values = new ArrayList<>();
try {
rs = st.executeQuery("SELECT * FROM adresses");
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
ArrayList<String> list = new ArrayList<>();
list.add(id);
list.add(name);
list.add(adress);
list.add(catagory);
values.add(list);
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
The main problem in you code is you are using arrays to save variable number of data. Arrays is fixed sized after they are created so you can't add (or remove) elements to them dynamically.
Instead of using arrays you should use an ArrayList object which have methods to add more elements. Also instead of creating a multidimensional array it looks like a better idea to create a class for the data you get from you database.
So lets first create a Address class:
public class Address {
public String id, name, adress, catagory;
public Address(String id, String name, String adress, String catagory) {
this.id = id;
this.name = name;
this.adress = adress;
this.catagory = catagory;
}
}
Now you can write you code as:
public List<Address> getData() {
List<Address> values = new ArrayList<Address>();
try {
rs = st.executeQuery("SELECT * FROM adresses");
int i = 0;
while(rs.next()) {
String id = rs.getString("id");
String name = rs.getString("name");
String adress = rs.getString("email_adress");
String catagory = rs.getString("catarogy");
values.add(new Address(id, name, adress, catagory));
}
return values;
} catch (SQLException e) {
e.printStackTrace();
return values;
}
}
The returned list will contain a list of Address objects which have the values from you database. Also, the size of the list is always the same as the content you put into it.

removing duplicate records in list

Hi while developing one of my web application i am storing the user information in to an ArrayList based on sql query executed, it contain duplicate objects how to remove duplicate objects in list , i already tried some method but it still not working.
This Is My Code Correct me where i am wrong
public ArrayList loadData() throws ClassNotFoundException, SQLException {
ArrayList userList = new ArrayList();
String url = "";
String dbName = "";
String userName = "";
String password = "";
Connection con = null;
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement ps = null;
try {
String name;
String fatherName;
int Id;
String filePath;
int age;
String address;
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString(1);
fatherName = rs.getString(2);
age = rs.getInt(3);
address = rs.getString(4);
Id = rs.getInt(5);
filePath=rs.getString(6);
/* if(flag)
{
prev=Id;
flag=false;
}
else if(Id==prev)
{
TEMP=TEMP+";"+filePath;
}*/
//PhotoList = PhotoList(Id, con);
UserData list = new UserData();
list.setName(name);
list.setFatherName(fatherName);
list.setAge(age);
list.setAddress(address);
list.setId(Id);
// list.setFilePath(filePath);
userList.add(list);
}
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList al = new ArrayList();
HashSet hs = new HashSet();
hs.addAll(userList);
al.clear();
al.addAll(hs);
return al;
}
And My Bean Class contant is
public class UserData {
private String name;
private String fatherName;
private int Id;
//private String filePath;
private int age;
private String address;
public UserData()
{
}
public UserData(String name, String fatherName,int Id, int age,String address)
{
this.name = name;
this.fatherName = fatherName;
this.Id = Id;
//this.filePath=filePath;
this.age=age;
this.address=address;
}
//GETTER AND SETTER..
General Idea: Use Set, not List. But you must override hash and equals of the class.
If you want a Collection of objects that does not have a specific order and you don't want duplicates, it's better for you just to use a Set like for example HashSet, or, if in your set the order is important, the TreeSet.
Just remember to override the hash and equals methods.
if you add this to your bean everything should work:
public int hashCode() {
return (name + fatherName+ Id + filePath + age + address).hashCode();
}
public boolean equals(Object obj) {
return ( hashCode() == obj.hashCode() );
}
Your userdata class does not implement equals or hashcode. This means two instances created with the same values will not be counted as duplicates. This is why the set contains duplicates.
For example
UserData u1 = new UserData("Foo", "bar",1, 1,"baz");
UserData u2 = new UserData("Foo", "bar",1, 1,"baz");
u1 and u2 are not considered equal as they are different objects. Adding an equals and hashcode method should fix this. However even better is adarshr's idea of removing dupes in the SQL.
All duplicates must be removed at an SQL level. Your SQL is suggesting that it could be generating duplicate records.
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
What does the clause ID = USER_ID mean? Shouldn't you be passing in that value as an input to your query?
Also, is the column ID a primary key? Otherwise, use a where clause that doesn't generate duplicates.

newbie attempt to use Java ArrayList to store ResultSet obtained from database

I have a database server communicating with a Java application server using JDBC. I want to store data from the database ResultSet into Java variables.
Here's my Java class, HRPeople:
public class HRPeople {
public int elements;
public String[] FirstName;
public String[] LastName;
public String[] Email;
public int[] Salary;
}
I currently use this class to store data from ResultSet, as follows:
query = "SELECT first_name, last_name, email, salary FROM HR.Employees where rownum < 6";
rset = stmt.executeQuery(query);
while (rset.next()) {
returnHRdata.FirstName[ii] = rset.getString("first_name");
returnHRdata.LastName[ii] = rset.getString("last_name");
returnHRdata.Email[ii] = rset.getString("email");
returnHRdata.Salary[ii] = rset.getInt("salary");
ii = ii + 1;
}
The problem with the above scenario is that the primitive arrays require me to know the number of rows in the ResultSet so that I can properly initialize those arrays. So what I want to do is use an ArrayList instead. How would I modify the above scenario to do this?
Here's my initial attempt (is this close)? Is HRPeople.java file shown above even used in this scenario?
query = "SELECT first_name, last_name, email, salary FROM HR.Employees where rownum < 6";
rset = stmt.executeQuery(query);
List<HRPeople> returnHRdata = new ArrayList<HRPeople>();
while (rset.next()) {
returnHRdata.FirstName = rset.getString("first_name");
returnHRdata.LastName = rset.getString("last_name");
returnHRdata.Email = rset.getString("email");
returnHRdata.Salary = rset.getInt("salary");
returnHRdata.add;
}
UPDATE 1:
If I add to the code the following,
return returnHRdata;
I get the following error (any idea why?):
myClass.java:213: incompatible types
found : java.util.List<HRPerson>
required: java.util.ArrayList<HRPerson>
return returnHRdata;
^
1 error
You probably want to first define an HRPerson like this:
public class HRPerson {
public String firstName;
public String lastName;
public String email;
public int salary;
}
Then your main code would look like:
query = "SELECT first_name, last_name, email, salary FROM HR.Employees where rownum < 6";
rset = stmt.executeQuery(query);
List<HRPerson> returnHRdata = new ArrayList<HRPerson>();
while (rset.next()) {
HRPerson person = new HRPerson();
person.firstName = rset.getString("first_name");
person.lastName = rset.getString("last_name");
person.email = rset.getString("email");
person.salary = rset.getInt("salary");
returnHRdata.add(person);
}
List<HRPeople> returnHRdata = new ArrayList<HRPeople>();
while (rset.next()) {
HRPeople people = new HRPeople();
people.FirstName = rset.getString("first_name");
people.LastName = rset.getString("last_name");
people.Email = rset.getString("email");
people.Salary = rset.getInt("salary");
returnHRdata.add(people);
}
You can improve this code by using a lowerCase letter for your first char of your fields and using getters and setters to access them.
Convert this:
public class HRPeople {
public int elements;
public String[] FirstName;
public String[] LastName;
public String[] Email;
public int[] Salary;
}
to:
public class HRPerson {
public String firstName;
public String lastName;
public String email;
public int salary;
}
and:
List<HRPerson> people = new ArrayList<HRPerson>();
Now it should be easy:
while (rset.next()) {
HRPerson person = new HRPerson();
returnHRdata.firstName = rset.getString("first_name");
returnHRdata.lastName = rset.getString("last_name");
returnHRdata.email = rset.getString("email");
returnHRdata.salary = rset.getInt("salary");
people.add(person);
}
Close...
while (rset.next()) {
HRPeople person = new HRPeople();
person.setFirstName(rset.getString("first_name"));
person.setLastName(rset.getString("last_name"));
person.setEmail(rset.getString("email"));
person.setSalary(rset.getInt("salary"));
returnHRdata.add(person);
}
You of course must define the setXXXX methods on the HRPerson class. Oh yeah, and do what Thomasz suggested.
create a class HRPeople, which has firstname, lastname.... attributes, and declare getter, setters method.
then:
List<HRPeople> returnHRdata = new ArrayList<HRPeople>();
HRPeople people = null;
while (rset.next()) {
people = new HRPeople();
people.setFirstName( rset.getString("first_name"));
people.setLastName (rset.getString("last_name"));
...
returnHRdata.add(people);
}
Instead of storing an array of each property in your object, make a single object to describe a given entity in the table.
class HRPerson {
String firstName;
String lastName;
String email;
Integer salary;
}
Create a list of this type, allowing you to store the results.
List<HRPerson> hrPeople = new ArrayList<HRPerson>();
while(rset.next()) {
HRPerson person = new HRPerson();
person.firstName = rset.getString("first_name");
person.lastName = rset.getString("last_name");
person.email = rset.getString("email");
person.salary = rset.getInt("salary");
hrPeople.add(person);
}
Finally, fill it by creating new objects for each row in your table.

Categories