I would like to write a converter to convert my custom object to DTO and back. How do I approach it?
I have 2 classes Appointment and Doctor which is a subclass of Appointment. I would like to have the converter as simple as possible.
I am not looking for straight answer, would appreciate tips on how to approach it.
below classes have getters and setters:
public class Doctor {
private long id;
private String name;
private String surname;
private String key;
}
public class Appointment {
private long id;
private String description;
private Doctor doctor;
private Date appointmentDate;
}
//converter
public class ConverterComponent {
public AppointmentDTO convert(Appointment appointment){
AppointmentDTO appointmentDTO = new AppointmentDTO();
appointmentDTO.id = appointment.getId();
appointmentDTO.description = appointment.getDescription();
appointmentDTO.doctor = appointment.getDoctor().toString();
appointmentDTO.appointmentDate = appointment.getAppointmentDate().toString();
return appointmentDTO;
}
}
I would like to write another convert(AppointmentDTO appointmentDTO) method in ConverterComponent which will return the Appointment object back.
Could it be done just by parsing Object to json and back again?
Thanks,
Related
Hello i am currently studying and we got a task , we need to modify a video-shop wepsite and we got catalog class and some other classes to help it run with spring like catalogcontroller catalogdataintitlizer etc , here is a cut of the code
`#Entity
#Table(name = "COMMENTS")
public class Comment implements Serializable {
private static final long serialVersionUID = -7114101035786254953L;
private #Id #GeneratedValue long id;
private String text;
static int rating;
static double r_total;
private LocalDateTime date;
#SuppressWarnings("unused")
private Comment() {}
public Comment(String text, int rating, LocalDateTime dateTime ) {
this.text = text;
this.rating = rating;
this.date = dateTime;
` that was from a class called Comment and in this class there are the rating we need to get the Average rating from the rating on every video "note : when someone open a video you can leave a comment with a rating and we need to always add up all the rating that the user leave and then divide it on the number of users ,
`#Entity
public class Disc extends Product {
public static enum DiscType {
BLURAY, DVD;
}
private List<Comment> comments = new ArrayList<>();
#SuppressWarnings({ "unused", "deprecation" })
private Disc() {}
public Disc(String name, String image, Money price, String genre, DiscType type) {
super(name, price);
this.image = image;
this.genre = genre;
this.type = type;
}
public String getGenre() {
return genre;
}
public void addComment(Comment comment) {
comments.add(comment);
}
public Iterable<Comment> getComments() {
return comments;
}`
and here is the other class that might help too here we save the comments to a arraylist "note : i didnt type the code " we just got this project and we need to change few things and i have been spending alot alot of time trying to solve this problem but still no use
i tried to make object from disc in comment and use some of his methods but sadly i got whitelist error from spring when i press on any video so i tried to make the rating static and try to grab it from the other class it worked but when i change from video to other video i end up adding all videos togther " it stacks " i am really new to java and i dont really know what to do now xd ty in advance
To run the application i use tomcat 8.5.50 package in war.
i use spring 5.2 version.
in my code i want to use LocalDataTime like this:
#Entity
#Table(name="meals")
public class Meal {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "date_time")
#Convert(converter = MealConverter.class)
private LocalDateTime datetime;
#Column(name = "description")
private String description;
#Column(name = "calories")
private int calories;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public LocalDateTime getDatetime() {
return datetime;
}
public void setDatetime(LocalDateTime datetime) {
this.datetime = datetime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCalories() {
return calories;
}
public void setCalories(int calories) {
this.calories = calories;
}
}
my Converter:
#Converter(autoApply = true)
public class MealConverter implements AttributeConverter<Meal, String> {
private static final String SEPARATOR = ", ";
#Override
public String convertToDatabaseColumn(Meal meal) {
StringBuilder sb = new StringBuilder();
sb.append(meal.getCalories()).append(SEPARATOR)
.append(meal.getDatetime())
.append(SEPARATOR)
.append(meal.getDescription());
return sb.toString();
}
#Override
public Meal convertToEntityAttribute(String dbData) {
String[] rgb = dbData.split(SEPARATOR);
Meal meal = new Meal(Integer.valueOf(rgb[0]),
LocalDateTime(valueOf(rgb[1]),
rgb[2],
rgb[3]);
return meal;
}
}
I am trying to use the converter in the convertToEntityAttribute method but the compiler does not allow me to do this. What needs to be fixed in my Converter?
Meal meal = new Meal(Integer.valueOf(rgb[0]),
LocalDateTime(valueOf(rgb[1]),
rgb[2],
rgb[3]);
Your Meal class doesn’t seem to have any explicit constructor, so you cannot pass arguments to new Meal(). You seem to be trying to pass two arguments. You may want to create a suitable constructor, or you may want to pass the two values into the Meal using setters after the object has been created.
LocalDateTime is a class, but you seem to try to call it as a method with three arguments. If that’s java.time.LocalDateTime, you probably intended LocalDateTime.of(someArguemts), but there isn’t any three-argument of method of that class. If you explain better what result you expect, we can guide you better.
As the first argument to LocalDateTime you have a call to a valueOf method that doesn’t seem to be declared in your class. You may have intended Integer.valueOf as in the preceding line.
If you are trying to use your RGB values for initializing a date (don’t know what sense that might make), be aware that if your RGB values go up to 255, this will likely fail with an exception since month numbers only go up to 12 and day of month up to 31.
I am far from sure that the following is correct or does what you want it to do, but it’s a guess at what you may be after.
#Override
public Meal convertToEntityAttribute(String dbData) {
String[] fields = dbData.split(SEPARATOR);
Meal meal = new Meal();
meal.setCalories(Integer.parseInt(fields[0]));
meal.setDateTime(LocalDateTime.parse(fields[1]));
meal.setDescription(fields[2]);
return meal;
}
I am trying to do the opposite of your convertToDatabaseColumn method. I have discarded the variable name rgb because I didn’t see how it couldn’t be misleading here.
I have following DTOs:
#Data
public class PersonDTO implements Diffable<PersonDTO> {
private String id;
private String firstName;
private String lastName;
private List<AddressDTO> addresses;
#Override
public DiffResult diff(PersonDTO personDTO) {
return new DiffBuilder(this, personDTO, SHORT_PREFIX_STYLE)
.append("id", this.id, personDTO.getId())
.append("firstName", this.firstName, personDTO.getFirstName())
.append("lastName", this.lastName, personDTO.getLastName())
.append("addresses", addresses, personDTO.getAddresses())
.build();
}
}
#Data
public class AddressDTO implements Diffable<AddressDTO> {
private String id;
private String personId;
private String addressType;
private String street;
private String houseNumber;
private String postalCode;
private String city;
private String countryId;
#Override
public DiffResult diff(AddressDTO addressDTO) {
return new DiffBuilder(this, addressDTO, SHORT_PREFIX_STYLE)
.append("id", this.id, addressDTO.getId())
.append("personId", this.personId, addressDTO.getPersonId())
.append("addressType", this.addressType, addressDTO.getAddressType())
.append("street", this.street, addressDTO.getStreet())
.append("houseNumber", this.houseNumber, addressDTO.getHouseNumber())
.append("postalCode", this.postalCode, addressDTO.getPostalCode())
.append("city", this.city, addressDTO.getCity())
.append("countryId", this.countryId, addressDTO.getCountryId())
.build();
}
}
My main goal is to find differences between two similar person objects. Currently I've tried to use Diffable interface from apache commons which is perfectly good for object. Please advise how to deal with collections when size of each collection can be different. For instance few addresses were removed, few was added and few was updated. Please see example below:
Probably there is another library which helps to achieve similar goals, please advice
source can be your first object
target can be your second object
Iterator targetIt = target.iterator();
for (Object obj:source)
if (!obj.equals(targetIt.next())
// Element has changed
I have an object extending SugarRecord that looks like this:
public class SavedDraft extends SugarRecord {
private String name;
private String difficulty;
private int sport_id;
private LocalActivity localActivity;
public SavedDraft() {
}
public SavedDraft(String name, String difficulty, int ID, LocalActivity localActivity) {
this.name = name;
this.difficulty = difficulty;
this.sport_id = ID;
this.localActivity = localActivity;
}
}
The problem is that I always get a null object when I try to get the localActivity object from the database (see: SavedDraft.findById(SavedDraft.class, 1).getLocalActivity()), and I'm just wondering if it's possible to save objects as parameters in SugarORM at all.
This would be a relationship and you would need the LocalActivity to extend SugarRecord also.
See the documentation of Book and Author: http://satyan.github.io/sugar/creation.html
after messing around with parsing a JSON response with GSON for a day, I finally figured out how to get my javabeans right in order to extract my data from the response. This is the layout of my nested classes and lists:
public class LocationContainer {
public class paging {
private String previous;
private String next;
}
private List<Datas> data;
public class Datas {
private String message;
private String id;
private String created_time;
public class Tags {
private List<Data> datas;
public class Data {
private String id;
private String name;
}
}
public class Application {
private String id;
private String name;
}
public class From {
private String id;
private String name;
}
public class Place {
private String id;
private String name;
public class Location {
private int longitude;
private int latitude;
}
}
}
}
Now I am trying to get a hold of the name string inside the place class and the created_time string, but since I am quite a noob, I can't seem to figure it out.
I was able to extract the created_time string by using
String time = gson.toJson(item.data.get(1).created_time);
However using
String name = gson.toJson(item.data.get(1).Place.name);
doesnt work.
The item class is an instance of LocationContainer filled with the output from GSON.
Any pointers would be greatly appreciated.
created_time is a member variable of Data, so your first line is fine.
However, Place is not a member variable, it's just a class definition. You probably need to instantiate a member variable inside your Data class, e.g.:
private Place place;