How to retrieve array from database - java

I have created json in javascript and I am putting this json in one array. I have stored the array in a database field named "exp_values" like :
[{"concentration":"5","answers":10},{"concentration":"5","answers":20},{"concentration":"5","answers":78}]
I want to retrieve from the database. I am using spring and I created pojo(bean) class like
public class ExperimentParameterBean {
private String username;
private String[] exp_values;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String[] getExp_values() {
return exp_values;
}
public void setExp_values(String[] arrayData) {
this.exp_values = arrayData;
}
}
I used hibernate for retrieving values from the database. I want this array as it is
in java. How can I do this? I have knowledge of spring and hibernate. I want to only get this array from the database in the JSONObject fromat.

my problem solved. i am storing json as text datatype in mysql

Related

How to use serialization to maintain a file to store objects

I've looked at many places on serialization but can't seem to find a solution to my problem. I'm making an Email client program and I want to store every email I send as an object in a file and then be able to retrieve it.
The problem I encounter is that every time I use ObjectOutputStream's writeObject() method, it truncates the file instead of appending it. Then I tried storing the emails in an ArrayList and storing the ArrayList in the file. Like, everytime I want to store I would readObject() the ArrayList then add the new email to it and then write the ArrayList again to the file. But this method started throwing many exceptions(i.e InvalidClassException).
Is there a way to serialize objects such that I will be able to append them to the file each time I want to write a new email or any other workaround for this?
Thanks in advance, below is the EmailMessage class:
public class EmailMessage implements Serializable{//implement serializables
private String recipient;
private String subject;
private String content;
private String date;
public void setRecipient(String recipient)
{
this.recipient=recipient;
}
public String getRecipient()
{
return this.recipient;
}
public void setSubject(String subject){
this.subject=subject;
}
public void setContent(String content){
this.content=content;
}
public String getSubject(){
return this.subject;
}
public String getContent(){
return this.content;
}
public void setDate(String date)
{
this.date=date;
}
public String getDate()
{
return this.date;
}
public String printDetails()
{
String details="Recipient: "+getRecipient()+
"\nSubject: "+getSubject()+
"\nEmail content: "+getContent()+
"\nDate Sent: "+getDate();
return details;
}
}

Getting getters from Java 17 subclasses, DTO

What could be the problem ?
I have a DTO class where I get john , after which I need to pull these values out of there and set them to another object.
Previously, I did it via VS code and everything worked fine. I moved these classes to the INTELLIJ IDEA after which I can't get the values from this class.
Example DTO UPDATE:
public class GetModel {
#JsonProperty("vendor")
private String vendor;
private List<Result> result = null;
//get/set
#JsonProperty("result")
public List<Result> getResult() {
return result;
}
#JsonProperty("result")
public void setResult(List<Result> result) {
this.result = result;
}
class Result {
#JsonProperty("FIELDS")
private Fields fields;
//get/set
class Fields {
#JsonProperty("adress")
private String adress;
//get/set
}
}
}
I am creating an object to set a value from a class GetModel
Example:
GetModel info;
Show show = new Show();
show.setAuthorityCyr(info.getResult().get(0).getFields().getAdress());
but I cannot get to it, respectively, and get the value.
the same project with the same code (only Java 11 was used) it gave these parameters.
Here Java 17 is used and does not give meaning.
Only in the context menu it shows incomprehensible fields as indicated in the image:
how to get to the values to set them in this case?
UPDATE
POJO :
public class Show {
// other fields
#JsonProperty("cyr")
private String authorityCyr;
#JsonProperty("cyr")
public String getAuthorityCyr() {
return authorityCyr;
}
#JsonProperty("cyr")
public void setAuthorityCyr(String authorityCyr) {
if(authorityCyr !=null){
this.authorityCyr = authorityCyr;
} else if(authorityCyr==null){
this.authorityCyr = "null";
}
}
// other get/set
}

About ArrayList in future use?

I am a java beginner and learning the oop concept. I already success to store the object value into a arraylist and i try to display the arraylist in the main method. But the problem is if i remove the add value code in the main method and display again the arraylist. The arraylist will show the null value which is []. Please help me and is this is my understanding problem or need to store in txtfile? database or what to get the or store the arraylist and can use for display all the record, update or delete that i add before
This is for my practice project and unuse the database to create a POS system based on oop concept. I had learn php and c# before and i do the same type project and not very confused because of using database. But now i feel confused how to use the java to create it and can has ability to create member, update member profile and etc based on oop concept. Please help me or give the suggestion. Very thank you.
my super class
class Person {
private List<Customer> customers;
private String name;
private String gender;
private String email;
public Person(){
}
public Person(List<Customer> customers){
this.customers = customers;
}
public Person(String name, String gender, String email){
***
}
public List<Customer> getCustomers(){
return customers;
}
public void addCustomer(Customer customer){
customers.add(customer);
}
//Getter
***
//Setter}
my subclass
class Customer extends Person{
private int custID;
private static int customerID = 10001;
public Customer(String name, String gender, String email,int custID){
super(name, gender, email);
this.custID = custID;
customerID++;
}
public int getCustID(){
return custID;
}
public static int getCustomerID(){
return Customer.customerID;
}
public String toString(){
return String.format("%d%30s%7s%30s\n", getCustID(), getName(), getGender(),getEmail());
}
}
My main method
public class POS {
public static void main(String[] args) {
Customer p1 = new
Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID());
Customer p2 = new
Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID());
List<Customer> cList = new ArrayList<>();
cList.add(p1); //if remove
cList.add(p2); // if remove
Person customer = new Person(cList);
System.out.print(customer.getCustomers());
}
}
i expect if write the code in main like
{ Person person = new Person();
System.out.print(person);
}
will display the result that i add before
If you don't want to add the customers to an ArrayList in your main-function a good way to do it would be to set the List<Customer> static in your Person-class and adding the customers as they get created.
public class Person {
private static List<Person> customers = new ArrayList<>();
public static List<Person> getCustomers() {
return customers;
}
private String name;
private String gender;
private String email;
public Person(String name, String gender, String email) {
this.name = name;
this.gender = gender;
this.email = email;
customers.add(this);
}
/* getters */
}
now in your main()-function you only have to create the Customers and they automatically get added to the customers list and therefore you can then get them by calling the static function getCustomers()
public static void main(String[] args) {
Customer p1 = new Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID());
Customer p2 = new Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID());
System.out.print(Customer.getCustomers());
}
To store them you would have to implement some kind of storage system like MySQL or simply a text file if you don't really have to access them from everywhere. You will find plenty of tutorials here on Stackoverflow in how to do that.
EDIT
#andy-turner pointed out that doing customers.add(this); inside a constructor really is a pain. So you could just create the ArrayList<Customer> in your Main-class and then work like this:
private static ArrayList<Customer> customers = new ArrayList<>();
public static void main(String[] args) {
customers.add(new Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID()));
customers.add(new Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID()));
System.out.print(customers);
}
Variables in memory are ephemeral
An ArrayList, like all of the Java Collections Framework, is a structure for holding data in memory. When your program ends its execution, all of that memory is freed. Your ArrayList is destroyed.
Storage
If you want to share data between runs, you must store it.
You can open a file in storage and write data values as text. On next run, read that file, parse the text back into objects, and populate a new ArrayList.
You can open a file and have your ArrayList write itself to storage using Java Serialization technology. Or you can do the serialization yourself with another serialization format.
Or send your data values to a database, which in turn writes them to storage. On next run, retrieve from database.
Or pass your data over the network to some service which accepts the data on your behalf. On next run, ask the service for your data.
All of this is too broad to discuss on Stack Overflow. You need to do your own research and learning.
Empty array versus NULL
The arraylist will show the null value which is [].
The string [] represents an empty array, an array holding no elements. Such array is not null! Null means no array at all.
Imagine a bookshelf holding books. That’s like an array holding elements. Remove the books. The empty shelf is like an empty array, with no elements. Now take down the bookshelf and burn it. That’s a null array, meaning no array at all.

Storing Objects of Class into an Array

I'm trying to store objects that have a username and password from the class "Driver" into an array list. When I try to print every value in the array to test whether they're being stored, it only prints the last value declared, numerous times. I have tried nearly every other solution on thee forums related to this issue and it just wont work :(
Code below:
package eDepotSystem;
import java.util.ArrayList;
public class Driver {
protected static String driverUserName;
protected static String driverPassWord;
public Driver (String userName, String passWord) {
driverUserName = userName;
driverPassWord = passWord;
}
public static void driverArray() {
ArrayList<Driver> driverList = new ArrayList<Driver>();
Driver driver = new Driver(driverUserName, driverPassWord);
driver.setUserName("driver1");
driver.setPassword("123");
driverList.add(driver);
driver = new Driver(driverUserName, driverPassWord);
driver.setUserName("driver2");
driver.setPassword("321");
driverList.add(driver);
Driver tempDriver = new Driver(driverUserName, driverPassWord);
for (int i = 0; i < driverList.size(); i++) {
tempDriver = driverList.get(i);
System.out.println(tempDriver);
}
}
public void setPassword(String password) {
driverPassWord = password;
}
public static String getUserName() {
return driverUserName;
}
#Override
public String toString() {
return driverUserName + driverPassWord;
}
}
I don't know whether my loop is wrong or the way I'm declaring the objects is wrong? Any help would be grand and thanks in advance!
your field variables should not be static.
It is being shared by all instances of Driver class (ie objects), hence it is printing the last value which you added.
Problem 1:
Your "instance variables" (username and password) are static. Therefore you only have one instance of them. If you print them out you must always get the same value.
Problem 2:
You only add one object. You add it once, change it's values and add it a second time. If you print it out you must get the same values ... even if you remove the statickeywords.
You should instead try something like this:
package eDepotSystem;
import java.util.ArrayList;
import java.util.List;
public class Driver {
private final String driverUserName;
private final String driverPassWord;
public Driver (String userName, String passWord) {
driverUserName = userName;
driverPassWord = passWord;
}
public static void driverArray() {
List<Driver> driverList = new ArrayList<Driver>();
driverList.add(new Driver("drv1", "pw1"));
driverList.add(new Driver("drv2", "pw2"));
for (Driver tempDriver : driverList) {
System.out.println(tempDriver);
}
}
}
The static keyword forces the driverUserName and driverPassWord variables to be instantiated only once in memory. While they are not constants, it makes any further additions to your list reference that first and only instance in memory, hence why it keeps showing the same value.
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

bean array eclipse scout sample

I am learning Eclipse Scout... I have connected to Sql server, fetching data using Object[][]...now, I want to fetch data using beans, beanarray holder...
I dont know the process...
I have created bean Users!
I have populated bean using service, using this example: http://www.eclipse.org/forums/index.php/t/310526/
So can someone explain how to use beans in scout, to populate table, or form...
Make a bean example: users
Fill the bean in service example: get user data from users table
populate table using that bean...
tnx
Java POJO (bean)
If you are working with plain old java object (POJO) like this:
public class User {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
You can populate an array of those POJO like this:
public User[] loadAll() throws ProcessingException {
BeanArrayHolder<User> beansArray = new BeanArrayHolder<User>(User.class);
SQL.selectInto(" select first_name, last_name " +
" from users " +
" into :{FirstName}, :{LastName} ", beansArray);
return beansArray.getBeans();
}
To populate your table, you need to do it by hand. For example on the client side:
for (User user : beansArray.getBeans()) {
ITableRow row = getTable().createRow();
getTable().getNameColumn().setValue(row, user.getLastName());
getTable().getFirstNameColumn().setValue(row, user.getFirstName());
getTable().addRow(row, true);
}
A mapping server side is also possible. But in this case, you should definitively consider to use table data (see the next section)
Table data
You should ensure that you are using bean based TableData. Read this answer to know how you can differentiate table based TableData and bean based TableData.
Assuming you have a UserTableField like this in your Form:
#Order(10.0)
#FormData(sdkCommand = FormData.SdkCommand.USE, value = AbstractTableFieldBeanData.class, defaultSubtypeSdkCommand = FormData.DefaultSubtypeSdkCommand.CREATE)
public class UserTableField extends AbstractTableField<UserTableField.Table> {
#Order(10.0)
public class Table extends AbstractExtensibleTable {
public LastNameColumn getLastNameColumn() {
return getColumnSet().getColumnByClass(LastNameColumn.class);
}
public FirstNameColumn getFirstNameColumn() {
return getColumnSet().getColumnByClass(FirstNameColumn.class);
}
#Order(10.0)
public class FirstNameColumn extends AbstractStringColumn {
#Override
protected String getConfiguredHeaderText() {
return TEXTS.get("FirstName");
}
}
#Order(20.0)
public class LastNameColumn extends AbstractStringColumn {
#Override
protected String getConfiguredHeaderText() {
return TEXTS.get("LastName");
}
}
}
}
You should be able to do something like that in your service:
UserTableRowData rowData = formData.getUserTable().addRow();
rowData.setFirstName("John");
rowData.setLastName("Smith");
Instead of adding the rows manualy, if you want to have a SQL query to populate the table, you can do something like that:
BeanArrayHolder<User> beansArray = new BeanArrayHolder<User>(User.class);
SQL.selectInto(" select first_name, last_name " +
" from users " +
" into :{UserTable.FirstName}, :{UserTable.LastName} ", formData);
It works the same way for TablePageData, see an example in our tutorial:
MiniCrm Tutorial > Write the first page > Load data on the server

Categories

Resources