implementation of inheritance in arraylist - java

addEmployee – This method will take Employee reference as parameter and add the same to the employees list after checking if employee with same id does not exist. It will return total employees count if addition is successful, else return -1.
public class Employee {
private int empId;
private String name;
private double basicPay;
private double perksPay;
public Employee()
{
}
public Employee(int empId, String name, double basicPay, double perksPay) {
super();
this.empId = empId;
this.name = name;
this.basicPay = basicPay;
this.perksPay = perksPay;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBasicPay() {
return basicPay;
}
public void setBasicPay(double basicPay) {
this.basicPay = basicPay;
}
public double getPerksPay() {
return perksPay;
}
public void setPerksPay(double perksPay) {
this.perksPay = perksPay;
}
public class Organization extends Employee
{
ArrayList<Employee> emp=new ArrayList<Employee>();
public int addEmployee(Employee e)
{
.......
}
}

The old java way:
public int addEmployee(Employee e) {
for (Employee employee : emp) {
if (e.getId() == employee.getId()) {
return -1;
}
}
emp.add(e);
return emp.size();
}
EDIT:
The Java8 way:
public int addEmployee(Employee e) {
List<Employee> alreadyInList = emp.stream().filter(em -> em.getId() == e.getId()).collect(Collectors.toList());
return alreadyInList.isEmpty() ? -1 : alreadyInList.size();
}

Related

org.springframework.orm.jpa.JpaSystemException: Error accessing field by reflection for persistent property

I am using Spring Boot (v 2.4.0) with Hibernate 5.4.24 and, when trying to get some information from my database, I keep getting this error message:
org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int es.uc3m.orders.model.Shoppingcart.usID] by reflection for persistent property [es.uc3m.orders.model.Shoppingcart#usID] : 1
It is kind of weird for me, because it only happens when I try to access the table Shoppingcart, since I can get informatin from the rest of the tables.
I also used the exact same entities with another project but, insetad of using Spring Boot, persistence was made with EntityManagers and it worked perfectly fine.
These are my entities:
Shoppingcart
#Entity
#NamedQuery(name="Shoppingcart.findAll", query="SELECT s FROM Shoppingcart s")
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
private int usID;
//bi-directional many-to-many association to Product
#ManyToMany
#JoinTable(
name="sc_has_product"
, joinColumns={
#JoinColumn(name="scID")
}
, inverseJoinColumns={
#JoinColumn(name="productID")
}
)
private List<Product> products;
//bi-directional one-to-one association to User
#OneToOne(mappedBy="shoppingcart")
private User user;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public int getusID() {
return this.usID;
}
public void setusID(int usID) {
this.usID = usID;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isNull() {
return getProducts().isEmpty();
}
User
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String address;
#Column(name="card_n")
private Long cardN;
private String city;
private String country;
private int cvv;
private String email;
private String exp;
private String name;
private String pass;
private String surname1;
private String surname2;
private String typeOfUser;
#Column(name="zip_code")
private int zipCode;
//bi-directional many-to-one association to Order
#OneToMany(mappedBy="user")
private List<Orders> orders;
//bi-directional many-to-one association to Product
#OneToMany(mappedBy="user")
private List<Product> products;
//bi-directional one-to-one association to Shoppingcart
#OneToOne(cascade=CascadeType.REMOVE)
#JoinColumn(name="ID", referencedColumnName="usID", insertable=false, updatable=false)
private Shoppingcart shoppingcart;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getCardN() {
return this.cardN;
}
public void setCardN(Long cardN) {
this.cardN = cardN;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public int getCvv() {
return this.cvv;
}
public void setCvv(int cvv) {
this.cvv = cvv;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExp() {
return this.exp;
}
public void setExp(String exp) {
this.exp = exp;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getSurname1() {
return this.surname1;
}
public void setSurname1(String surname1) {
this.surname1 = surname1;
}
public String getSurname2() {
return this.surname2;
}
public void setSurname2(String surname2) {
this.surname2 = surname2;
}
public int getZipCode() {
return this.zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public List<Orders> getOrders() {
return this.orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public Orders addOrder(Orders order) {
getOrders().add(order);
order.setUser(this);
return order;
}
public Orders removeOrder(Orders order) {
getOrders().remove(order);
order.setUser(null);
return order;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Product addProduct(Product product) {
getProducts().add(product);
product.setUser(this);
return product;
}
public Product removeProduct(Product product) {
getProducts().remove(product);
product.setUser(null);
return product;
}
public Shoppingcart getShoppingcart() {
return this.shoppingcart;
}
public void setShoppingcart(Shoppingcart shoppingcart) {
this.shoppingcart = shoppingcart;
}
public String getTypeOfUser() {
return typeOfUser;
}
public void setTypeOfUser(String typeOfUser) {
this.typeOfUser = typeOfUser;
}
}
This is the ShoppingcartDAO class:
public interface ShoppingCartDAO extends CrudRepository<Shoppingcart, Integer> {
#Query("SELECT s FROM Shoppingcart s JOIN User u ON u.id = s.usID AND u.id LIKE :id")
Shoppingcart findByUser(#Param("id") int id);
#Query("SELECT s FROM Shoppingcart s")
List<Shoppingcart> findAllShoppingCart();
}
And, finally, this is my ShoppingcartController class:
#RestController
#CrossOrigin
#EnableAutoConfiguration
public class ShoppingCartController {
#Autowired
ShoppingCartDAO scDAO;
#RequestMapping(value = "sc", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<?> assignShoppingCart(#RequestBody(required = true) Shoppingcart sc) {
try {
scDAO.save(sc);
return new ResponseEntity<Void>(HttpStatus.CREATED);
} catch(Exception e) {
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
#RequestMapping(value = "sc", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<?> getEveryShoppingCart() {
try {
List<Shoppingcart> sc = scDAO.findAllShoppingCart();
return new ResponseEntity<List<Shoppingcart>>(sc, (sc != null) ? HttpStatus.OK : HttpStatus.NOT_FOUND);
} catch(Exception e) {
System.out.println(e);
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
}
}
}
I am really going nuts as I can´t figure out what is going on with my code, so thank you in advance if you help me.
I finally fixed it. For those of you who are wondering how, I deleted the relationships between tables that I had, ending with:
Shoppingcart:
#Entity
public class Shoppingcart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int scID;
#Column(name = "usID")
private Integer userID;
public Shoppingcart() {
}
public int getScID() {
return this.scID;
}
public void setScID(int scID) {
this.scID = scID;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
Product:
#Entity
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int productID;
private String category;
private String color;
private String description;
private String estadoProducto;
private String fecha;
private int orderID;
private String photo;
private double price;
private int seller;
private String sexo;
private String state = "Disponible";
private String talla;
private String title;
public Product() {
}
public int getProductID() {
return this.productID;
}
public void setProductID(int productID) {
this.productID = productID;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEstadoProducto() {
return this.estadoProducto;
}
public void setEstadoProducto(String estadoProducto) {
this.estadoProducto = estadoProducto;
}
public String getFecha() {
return this.fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getPhoto() {
return this.photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSexo() {
return this.sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getTalla() {
return this.talla;
}
public void setTalla(String talla) {
this.talla = talla;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public int getSeller() {
return seller;
}
public void setSeller(int seller) {
this.seller = seller;
}
With this, everything worked fine, but don't ask me why, because I don't know it.
Your Getters/Setters are wrongly implemented.
Like :
Actual :
public int getusID() {
return this.usID;
}
Expected :
public int getUsID() {
return this.usID;
}
Same with setter

Hardcoding values in Java

Currently I'm trying to Hardcode some values for a family tree application in Java.
Just need some ideas on how to go about it, not sure how to proceed.
I have also included the constructor classes:
public class TreeImpl {
private FamilyMember root;
public FamilyMember getRoot() {
return root;
}
public void setRoot(FamilyMember root) {
this.root = root;
}
public List<FamilyMember> getAllMembers() {
return allMembers;
}
public void setAllMembers(List<FamilyMember> allMembers) {
this.allMembers = allMembers;
this.setRoot(this.allMembers.get(0));
}
private List<FamilyMember> allMembers = new ArrayList<>();
public TreeImpl(FamilyMember root)
{
this.root=root;
addMembers(root);
}
private void addMembers(FamilyMember node)
{
if(node==null) return;
allMembers.add(node);
addMembers(node.getFather());
addMembers(node.getMother());
addMembers(node.getSpouse());
for(FamilyMember child : node.getChildren())
addMembers(child);
}
public void addSpouse(int index, FamilyMember spouse)
{
for(FamilyMember member : allMembers)
{
if(member.getMemberID()==index)
{
member.setSpouse(spouse);
allMembers.add(spouse);
return;
}
}
}
public void addFather(int index, FamilyMember father)
{
for(FamilyMember member : allMembers)
{
if(member.getMemberID()==index)
{
member.setFather(father);
allMembers.add(father);
return;
}
}
}
public void addMother(int index, FamilyMember mother)
{
for(FamilyMember member : allMembers)
{
if(member.getMemberID()==index)
{
member.setMother(mother);
allMembers.add(mother);
return;
}
}
}
public void addChild(int index, FamilyMember child)
{
for(FamilyMember member : allMembers)
{
if(member.getMemberID()==index)
{
member.setSpouse(child);
allMembers.add(child);
return;
}
}
}
public FamilyMember getDetailsForMember(String member)
{
for(FamilyMember m : this.getAllMembers())
{
if(m.getFirstName().equals(member))
return m;
}
return null;
}
My constructor class
public class FamilyMember implements Serializable{
private static int id=1;
private String firstName, surName, surNameAfterMarriage, life;
private Gender gender;
private Address address;
private FamilyMember mother, father, spouse;
private int memberID;
public boolean hasSub()
{
return (this.getFather()!=null || this.getMother()!=null || this.getChildren().size()>0);
}
public int getMemberID() {
return memberID;
}
public void setMemberID(int memberID) {
this.memberID = memberID;
}
private List<FamilyMember> children, grandChildren;
public static int getId() {
return id;
}
public static void incrementId()
{
id++;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurNameAfterMarriage() {
return surNameAfterMarriage;
}
public void setSurNameAfterMarriage(String surNameAfterMarriage) {
this.surNameAfterMarriage = surNameAfterMarriage;
}
public String getLife() {
return life;
}
public void setLife(String life) {
this.life = life;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public FamilyMember getMother() {
return mother;
}
public void setMother(FamilyMember mother) {
this.mother = mother;
}
public FamilyMember getFather() {
return father;
}
public void setFather(FamilyMember father) {
this.father = father;
}
public FamilyMember(String firstName, String surName, String surNameAfterMarriage, String life, Gender gender,
Address address) {
super();
this.firstName = firstName;
this.surName = surName;
this.surNameAfterMarriage = surNameAfterMarriage;
this.life = life;
this.gender = gender;
this.address = address;
this.memberID = this.getId();
this.children = new ArrayList<>();
this.incrementId();
}
for(FamilyMember child : this.getChildren())
{
text = text + " " + child.firstName;
}
return text;
}
public FamilyMember getSpouse() {
return spouse;
}
public void setSpouse(FamilyMember spouse) {
this.spouse = spouse;
}
public List<FamilyMember> getChildren() {
return children;
}
public void setChildren(List<FamilyMember> childer) {
this.children = childer;
}
public void addChild(FamilyMember child) {
this.children.add(child);
}
public List<FamilyMember> getGrandChildren() {
return grandChildren;
}
public void setGrandChildren(List<FamilyMember> grandChildren) {
this.grandChildren = grandChildren;
}
}
For examples, I want to add details for father, mothers, child etc so when I run the program, these values are displayed
Eg: Familymember father = new Familymember ("xyz". "xyx" )
You can set values using Constructor,
public FamilyMember (Gender gen,Address add,FamilyMember fmm,FamilyMember fmf,FamilyMember fms,int mId){
this.gender = gen;
this.address = add;
this.mother = fmm;
this.father = fmf;
this.spouse = fms;
this.memberID = mId;
}
it will set the FamilyMember object with hard coded values,
FamilyMember fm = new FamilyMember(Gender.MALE,add,fmm,fmf,fms,menId);
Let me know if any quires.
If you really want it through a constructor, you could do it this way:
// Secondary constructor
public FamilyMember() {
this("Paul", "Stevenson", ...); // calls the primary constructor
}
public FamilyMember(String firstName, String surName, String surNameAfterMarriage, String life, Gender gender,
Address address) {
// your primary constructor
}
Unfortunately this isn't very flexible. An alternative is to use a static method :
public static FamilyMember familyMemberSteve() {
return new FamilyMember("Steve", ...)
}
But to be honest, I wouldn't recommend this either. Like I said in the comment, it would be better to use XML or another format, because it would be more flexible.
Create a a static method in FamilyMember class that creates a family and then call this method before initialising a TreeImpl object.
public static FamilyMember createFirstFamilyNode() {
FamilyMember mother = new FamilyMember("Mother", ...);
FamilyMember father = new FamilyMember("Father", ...);
mother.setSpouce(father);
FamilyMember child1 = new FamilyMember("First Child", ...);
mother.addChild(child1);
// And so on for rest of family members
return mother;
}

Collections.sort() Method not working

While sorting an arraylist of Customer Class(user defined) having name and age as attributes on the basis of name, Collections.sort() method is showing error that "the type java.util.Comparator is not resolved.it is indirectly referenced from required .class file.
package comparable;
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> custtlist=new ArrayList<Customer>();
Customer c1=new Customer("vikas",1);
Customer c2=new Customer("mittal",2);
custtlist.add(c1);
custtlist.add(c2);
System.out.println("Before Sorting");
Iterator<Customer> iterator = custtlist.iterator();
while(iterator.hasNext()){
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustname());
}
Collections.sort(custtlist);
System.out.println("After Sorting");
iterator = custList.iterator();
while (iterator.hasNext()) {
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustName());
}
}
}
//Customer Class
package comparable;
public class Customer implements Comparable<Customer> {
private String custname;
private int age;
public Customer(String custname, int age) {
this.custname = custname;
this.age = age;
}
public Customer() {
}
public String getCustname() {
return custname;
}
public void setCustname(String custname) {
this.custname = custname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Customer c){
return this.custname.compareTo(c.getCustname());
}
}
You have an awful lot of typos in the code. After I corrected them, the compilation was successful. I took the liberty to make some improvements and styling.
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> customersList = new ArrayList<Customer>();
Customer c1 = new Customer("vikas", 1);
Customer c2 = new Customer("mittal", 2);
customersList.add(c1);
customersList.add(c2);
System.out.println("Before Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
Collections.sort(customersList);
System.out.println("\nAfter Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
}
}
public class Customer implements Comparable<Customer> {
private String name;
private int age;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public Customer() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Customer c){
return this.name.compareTo(c.getName());
}
}

How to iterate the arraylist of diffrent objects

In an ArrayList I have two different objects,
Student and Employee. I want to iterate through them one by one. I am able to iterate through the list and use the Employee objects but not the Student objects.
I have the following code:
package javaCollections;
import java.util.ArrayList;
import java.util.Iterator;
class Employee {
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
Employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class Student {
#Override
public String toString() {
return "student [stud_name=" + stud_name + ", rollNumber=" + rollNumber
+ "]";
}
String stud_name;
int rollNumber;
public Student(String stud_name, int rollNumber) {
super();
this.stud_name = stud_name;
this.rollNumber = rollNumber;
}
public String getStud_name() {
return stud_name;
}
public void setStud_name(String stud_name) {
this.stud_name = stud_name;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
}
public class Arraylist {
ArrayList<Object> emparray;
public void addemp() {
Employee emp = new Employee("abc", 12);
emparray = new ArrayList<Object>();
emparray.add(emp);
Employee emp1 = new Employee("def", 12);
emparray.add(emp1);
Student std = new Student("efg", 123);
Student std1 = new Student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
/*
* Iterator<Object> itr=emparray.iterator();
*
* while(itr.hasNext()) { System.out.println(itr.next()); }
*/
for (Object e : emparray) {
System.out.println(((Employee) e).getAge());
System.out.println(((Employee) e).getName());
}
}
public static void main(String[] args) {
Arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}
can someone please help me on this?
What you need to do is check the instance of the object.
for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
// do something else
}
}
}
IMO this is a bad design.
The best practice is to create common base called Person that has shared fields like name. Then you can replace Object with Person in the loop.
import java.util.ArrayList;
import java.util.Iterator;
interface Person{
public String getName();
public void setName(String name);
}
class employee implements Person{
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class student implements Person{
#Override
public String toString() {
return "student [stud_name=" + name + ", rollNumber=" + rollNumber
+ "]";
}
String name;
int rollNumber;
public student(String stud_name, int rollNumber) {
super();
this.name = stud_name;
this.rollNumber = rollNumber;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name=name;
}
}
public class arraylist {
ArrayList<Person> emparray;
public void addemp() {
employee emp = new employee("abc", 12);
emparray = new ArrayList<Person>();
emparray.add(emp);
employee emp1 = new employee("def", 12);
emparray.add(emp1);
student std = new student("efg", 123);
student std1 = new student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
for (Person e : emparray) {
if (e instanceof employee) {
System.out.println(((employee) e).getAge());
}else{
/// do for student
}
System.out.println(e.getName());
}
}
public static void main(String[] args) {
arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}
for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
System.out.println(((student) e).getRollNumber());
System.out.println(((student) e).getStud_name());
}
}
}

map 2 collection types using modelmapper

I am developing and spring application and for object mapping I am using ModelMapper library.
I am able to map basic class mapping but when I am trying to map 2 collection elements, source is set of enumeration with additional property like name and description and destination is pojo having id, name and description.
I have tried typemap and converters in mapping profile but I am getting exception of mapper.
And the source class is from other application(whose dependency have been added in pom.xml). I also don't want source type as an argument in setter of destination.
Ex.
SOURCE:
public class VType{
private int id;
private String name;
private String description;
}
public class VDTO{
private Set<VType> vTypes;
public Set<VType> getVTypes(){
return this.vTypes;
}
public void setVType() { //here I don't want to pass source type as an argument
//code stuff that I don't know what to do here
}
}
SOURCE ENUM:
public enum SourceVType{
V1(1, "Name1", "Desc1");
V2(2, "Name2", "Desc2");
private Integer id;
private String name;
private String description;
SourceVType(Integer id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
//getter-setter
}
Have you tried converter feature of modelmapper. You can use typemap converter to achieve this requirement.
#RunWith(JUnit4.class)
public class TempTest {
#Test
public void TestThis(){
final ModelMapper mapper = new ModelMapper();
mapper.addMappings(new PropertyMap<SrcClass, DestClass>() {
#Override
protected void configure() {
this.map().setId(this.source.getId());
this.map().setName(this.source.getName());
mapper.createTypeMap(TypeEnum.class, TypeClass.class).setConverter(
new Converter<TypeEnum, TypeClass>() {
#Override
public TypeClass convert(MappingContext<TypeEnum, TypeClass> mappingContext) {
if (mappingContext.getSource() == null) {
return null;
}
TypeEnum typeEnum = mappingContext.getSource();
TypeClass typeClass = new TypeClass();
typeClass.setId(typeEnum.getId());
typeClass.setName(typeEnum.getName());
return typeClass;
}
});
}
});
SrcClass srcObj = new SrcClass();
srcObj.setId(1);
srcObj.setName("name");
srcObj.setTypes(new HashSet<>(Arrays.asList(TypeEnum.TYPE1, TypeEnum.TYPE2)));
DestClass dstObj = mapper.map(srcObj, DestClass.class);
Assert.assertEquals(srcObj.getId(), dstObj.getId());
Assert.assertEquals(srcObj.getName(), dstObj.getName());
Assert.assertEquals(srcObj.getTypes().size(), dstObj.getTypes().size());
for(TypeClass c : dstObj.getTypes()) {
TypeEnum e = TypeEnum.getById(c.getId());
Assert.assertNotNull(e);
Assert.assertTrue(srcObj.getTypes().contains(e));
}
}
public static <Source, Result> Set<Result> convertAll(Set<Source> source, Function<Source, Result> projection)
{
Set<Result> results = new HashSet<>();
if(source == null) return results;
for (Source element : source)
{
results.add(projection.apply(element));
}
return results;
}
public static class SrcClass{
private Integer id;
private String name;
private Set<TypeEnum> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeEnum> getTypes() {
return types;
}
public void setTypes(Set<TypeEnum> types) {
this.types = types;
}
}
public static class DestClass{
private Integer id;
private String name;
private Set<TypeClass> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeClass> getTypes() {
return types;
}
public void setTypes(Set<TypeClass> types) {
this.types = types;
}
}
public static enum TypeEnum{
TYPE1(1, "Type 1")
, TYPE2(2, "Type 2")
, TYPE3(3, "Type 3")
, TYPE4(4, "Type 4");
private Integer id;
private String name;
TypeEnum(Integer id, String name) {
this.id = id;
this.name = name;
}
private static final Map<Integer, TypeEnum> byId = new HashMap<>();
private static final Map<String, TypeEnum> byName = new HashMap<>();
static {
for (TypeEnum e : TypeEnum.values()) {
if (byId.put(e.getId(), e) != null) {
throw new IllegalArgumentException("duplicate id: " + e.getId());
}
if (byName.put(e.getName(), e) != null) {
throw new IllegalArgumentException("duplicate name: " + e.getName());
}
}
}
public Integer getId() {
return this.id;
}
public String getName() { return this.name; }
public static TypeEnum getById(Integer id) {
return byId.get(id);
}
public static TypeEnum getByName(String name) {
return byName.get(name);
}
}
public static class TypeClass{
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

Categories