Pass a list of string to a declared class file - java

Hi All below is my Employeeinformation class file java. I have to pass the values to it through java code
I am fine passing the strings but i am unable to pass list of technologies and list of strings.
Technologies.java
package com.ElasticSearchCrud.ElasticSearchCrud;
import lombok.Data;
#Data
public class Technologies {
private String name;
private String yearsOfExperience;
}
Employeeinformation.java
package com.ElasticSearchCrud.ElasticSearchCrud;
import lombok.Data;
import java.util.List;
#Data
public class EmployeeInformation {
private String id;
private String firstName;
private String lastName;
private List<Technologies> technologies;
private List<String> emails;
public EmployeeInformation(String id, String firstName, String lastName, List<Technologies> technologies, List<String> emails) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.technologies = technologies;
this.emails = emails;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public List<Technologies> getTechnologies() {
return technologies;
}
public void setTechnologies(List<Technologies> technologies) {
this.technologies = technologies;
}
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
}
Passing a value to class file
EmployeeInformation EmployeePost = new EmployeeInformation("3", "Vignesh", "Murali","?","?");
How to pass the list of technologies and list of string in above code. Could some one help me tho achieve this?

List<Technologies> technologies = new ArrayList<>();
technologies.add(new Technologies("name1", "1999"));
technologies.add(new Technologies("name2", "1999"));
List<String> emails = new ArrayList<>();
strs.add("one");
strs.add("two");
EmployeeInformation EmployeePost = new EmployeeInformation("3", "Vignesh", "Murali",technologies,emails);
Also add #AllArgsConstructor to Technologies class. Or use setters to init Technologies objects:
#Data
#AllArgsConstructor
public class Technologies {
private String name;
private String yearsOfExperience;
}

#Data annotation has inner #RequiredArgsConstructor. This constructor is created with all non-initialized FINAL properties.
If you have not final properties there will be empty constructor.
So you have 3 ways:
Set you fields as final: new SomeObject(List.of("1","2"));
Add #AllArgsConstuctor: result the same
Leave as it is and initialize an object by set methods
SomeObject obj = new SomeObject();
obj.setList(List.of("1", "2"));

Related

H2 database columns and values don't converge JAVA Spring

I am new one at java and spring framework and have this problem. I have class, which has fields, that should be columns in H2. It looks like this:
package com.bankapp.bankwebapplication.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class PersonClient implements Client {
#Id
#Column(nullable = false, unique = true)
private Long id;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
#Column(nullable = false)
private String firstName;
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
#Column(nullable = false)
private String lastName;
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
#Column(nullable = false)
private String address;
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
#Column
private String workPhone;
public String getWorkPhone() { return workPhone; }
public void setWorkPhone(String workPhone) { this.workPhone = workPhone; }
#Column
private String homePhone;
public String getHomePhone() { return homePhone; }
public void setHomePhone(String homePhone) { this.homePhone = homePhone; }
#Override
public void getDetails() {
}
}
Also, I have data.sql file that inserts 1 value into that table:
INSERT INTO person_client VALUES (1, 'firstName', 'lastName', 'paper street', '+123123', '+321321')
So, the problem is that it looks like this:
Why? And how can I fix that?
Always specify the target columns in INSERT statements:
INSERT INTO person_client
(id, first_name, last_name, address, home_phone, work_phone)
VALUES
(1, 'firstName', 'lastName', 'paper street', '+123123', '+321321')
If you don't specify the target columns, the values are matched by position and apparently the columns are created in a different order than you think they are.
agree with #a_horse_with_no_name, if you not specify column names it will insert based on the position/index. And all your java variables are in string that is the reason it does't throw any classcast exception.

How to serialize select class fields to JSON string using the Builder Pattern in Java and Gson?

I created a User class with a Builder Pattern for the purpose of serializing it to a JSON String for POST. Now, the requirements have changed and I need the ability to PATCH an existing record, updating one or more fields but not all fields in a recordset. The example below has 5 fields in its User class but imagine if it had 30 or even 40 fields including the int type.
import com.google.gson.*;
class User
{
//All final attributes
private final String firstName;
private final String lastName;
private final int age;
private final String phone;
private final String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
//All getter, and NO setter to provide immutability
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
public static class UserBuilder
{
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
public UserBuilder() {
}
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public UserBuilder lastName(String lastName) {
this.firstName = lastName;
return this;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
//Return the finally consrcuted User object
public User build() {
User user = new User(this);
return user;
}
}
}
public class TestUserBuild {
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User.UserBuilder().
//No last name
//No age
//No phone
//no address
.firstName("Super")
.build();
System.out.println(user); // User: Super, null, 0, null, null
Gson gson = new Gson();
System.out.println(gson.toJson(user)); // {"firstName":"Super","age":0}
}
}
I didn't specify the age and, yet, there it is in the JSON string. I thought the builder pattern would facilitate creating any number of JSON string permutations, i.e. update the first name and last name, update the first name only, update the age only, update last name and phone number only, etc...
Is the builder pattern approach not the correct solution for this problem? If it is an acceptable solution, how can I leverage the builder pattern to serialize the User class to a JSON string but with only the fields of my choosing? Is there something I can leverage in the Gson library to realize this task such as creating a custom type adapter? Maybe I can create a custom type adapter that takes all field as inputs, checks if each one is NULL, or 0 for Integers, and then build the JSON string with just the deltas.
Your "age" field is worth 0 because "int" has a default value. Use "Integer" if you want the age field to default to null.
Some of the advantages of the Builder pattern are immutability (you can choose to allow a class to be modified only at creation time by the builder, removing all setters from the class), and that it's more concise for instantiating a class with multiple attributes.
But you don't need to keep your Builder pattern immutable. If I understand your need correctly, you could keep the builder pattern for versatility during object creation, and keep the setters on the class to be able to update fields easily.
import com.google.gson.*;
class User {
//Your attributes don't need to be final
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
//getters AND setters (omitted for brevity)
//builder class stays as is, omitted for brevity
public class TestUserBuild {
public static void main(String[] args) {
User user = new User.UserBuilder()
.firstName("Super")
.build();
//when you need to update
user.setAge(42);
}
}
The question is, why do you want immutability if you need to update fields periodically? Should you remove the immutability constraint altogether (by leaving setters in the class)? Do you need to be able to update specific combinations of fields according to particular business rules? If the latter is true, I would recommend moving away from an anemic model (a "bag of getters and setters") and adding domain-specific methods which take care of updating the relevant fields. Your User class would then look like this:
class User {
//Your attributes don't need to be final
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
//getters ONLY (omitted for brevity)
//no setters, only domain-relevant methods which update fields as needed
public void setIdentity(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setCoordinates(String phone, String address) {
this.phone = phone;
this.address = address;
}
}
//builder class stays as is
public class TestUserBuild {
public static void main(String[] args) {
User user = new User.UserBuilder()
.firstName("Super")
.build();
//update identity (say, your frontend has an "identity" page with only firstName and lastName on it
user.setIdentity("Chris", "Neve");
//your frontend page allowing user to update coordinates
user.setCoordinates("+331231231", "7th av, NYC");
}
}

Adding arraylist object to combobox [duplicate]

This question already has answers here:
How do I populate a JComboBox with an ArrayList?
(8 answers)
Closed 6 years ago.
I've created a JCombobox using Netbeans drag and drop.
I have an ArrayList<Person>.
How do I automatically add the FirstName of the Person into the combobox.
The code generated by Netbeans cant be edited in Source view.
Step 1: Lets say you have the following Person class.
Person.java
public class Person {
private int id;
private String firstName;
private String lastName;
public Person() {
}
public Person(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
#Override
public String toString() {
return firstName;
}
}
Step 2: Create the instance of JComboBox and set the model.
java.util.List<Person> list=new java.util.ArrayList<Person>();
list.add(new Person(1, "Sanjeev", "Saha"));
list.add(new Person(2, "Ben", "Yap"));
JComboBox<Person> comboBox = new JComboBox<Person>();
comboBox.setModel(new DefaultComboBoxModel<Person>(list.toArray(new Person[0])));
Step 3: Run your program.
public class PersonBox{
List<Person> person= new ArrayList<Person>();
JCombobox box; //=new JCombobox(...) ?
//used to add a new Person to the box
public void addPerson(Person person){
person.add(person);
/*
*gets the lass element in the list and adds the first
*name of this specific element into the box
*/
box.addItem(person.get(person.size()-1).getFirstName());
}
}
public class Person{
String firstName,sureName;
public Person(String firstName, String sureName){
this.firstName = firstName;
this.sureName = sureName;
}
public String getFirstName(){
return this.firstName;
}
public String getSureName(){
return this.sureName;
}
}

Getters: difference between "return firstName.get();" and "return firstName;" [duplicate]

This question already has an answer here:
When to use JavaFX properties setter and getter, instead of using the property directly
(1 answer)
Closed 7 years ago.
What is the difference between these two lines?
return firstName.get();
return firstName;
When should I use one or the other?
Here you have two classes where those lines are used:
package application.model;
import javafx.beans.property.StringProperty;
public class Employee {
private int id;
private String firstName,lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public StringProperty firstNameProperty() {
return firstName;
}
}
package ch.makery.address.model;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Model class for a Person.
*
* #author Marco Jakob
*/
public class Person {
private final StringProperty firstName;
private final StringProperty lastName;
private final StringProperty street;
private final IntegerProperty postalCode;
private final StringProperty city;
private final ObjectProperty<LocalDate> birthday;
/**
* Default constructor.
*/
public Person() {
this(null, null);
}
/**
* Constructor with some initial data.
*
* #param firstName
* #param lastName
*/
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
// Some initial dummy data, just for convenient testing.
this.street = new SimpleStringProperty("some street");
this.postalCode = new SimpleIntegerProperty(1234);
this.city = new SimpleStringProperty("some city");
this.birthday = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public String getStreet() {
return street.get();
}
public void setStreet(String street) {
this.street.set(street);
}
public StringProperty streetProperty() {
return street;
}
public int getPostalCode() {
return postalCode.get();
}
public void setPostalCode(int postalCode) {
this.postalCode.set(postalCode);
}
public IntegerProperty postalCodeProperty() {
return postalCode;
}
public String getCity() {
return city.get();
}
public void setCity(String city) {
this.city.set(city);
}
public StringProperty cityProperty() {
return city;
}
public LocalDate getBirthday() {
return birthday.get();
}
public void setBirthday(LocalDate birthday) {
this.birthday.set(birthday);
}
public ObjectProperty<LocalDate> birthdayProperty() {
return birthday;
}
}
In short: It depends on the context.
You may only use .get() when the object has a method get. String objects are very similar to primitives, they are a value and as such can be returned directly (they don't have a get method at all).
Here, StringProperty is a wrapper around (assumedly) a String, meaning if you were to return firstName; from the Person class, you would get a StringProperty instance, not a String - which most likely cannot be used in most operations. So, you return whichever datatype you need.
Note that if you were working with strings in both the source and destination classes, you could just return the value directly, it's already in usable form.

To form Json from nested POJOS

I have nested POJO as below. All the POJO's are in the same package. Please see student is is the name pojo and all other POJO are inside
class Student{
String firstName;
String lastName;
List <Activities> activites;
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;
}
public List<Activities> getActivites() {
return activites;
}
public void setActivites(List<Activities> activites) {
this.activites = activites;
}
}
class Activites{
List<Quipments> quipments;
String time;
public List<Quipments> getQuipments() {
return quipments;
}
public void setQuipments(List<Quipments> quipments) {
this.quipments = quipments;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
class Quipments{
String Type;
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
}
I want to convert the above student POJO in json that will have all the values of other pojo.
We are not suppose to use below api. I know the below one works.
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONMarshaller;
Want to use something like below
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
Please advice
Use this very popular library https://github.com/google/gson:
String sample = "{firstName: \"mardar\", lastName: \"pandit\"}";
com.google.gson.Gson gson = new com.google.gson.Gson();
Student student = gson.fromJson(sample, Student.class);
System.out.println(gson.toJson(student));

Categories