I have two pojos.
public class Pojo1 implements Serializable {
private static final long serialVersionUID = 1302290920579795856L;
private Long id;
private String idNumber;
private String vendorNumber;
private Date expires;
// Getters and setters for each one
}
public class Pojo2 implements Serializable {
private static final long serialVersionUID = 1302290920579795856L;
private Long id;
private String idNumber;
private String vendorNumber;
private Date expires;
private String otherData;
// Getters and setters for each one
}
Is there a Java API that I can use to create a Pojo1 from a Pojo2 automatically?
I.e.:
Pojo1 newPojo1 = SomeLibrary.fromPojoWithLikeNamedFields(pojo2);
// newPojo1 now has all the fields that had the same name from pojo2
won't a copy constructor do the job?,
public Pojo1(Pojo2 pojo2){
this.id = pojo2.getId();
this.idNumber = pojo2.getIdNumber();
this.vendorNumber = pojo2.getVendorNumber();
this.expires = pojo2.getExpires();
}
and then use as such,
Pojo1 newPojo1 = new Pojo1(pojo2);
or am I misunderstanding something...?
Related
public class MessageRqDTO implements Serializable {
private Long id;
private String data;
private String device;
private String headers;
private Boolean isProcessed;
private String notification;
private String referenceCode;
private Boolean scheduled;
private Boolean transactional;
private Instant startFromTime;
private Instant expirationTime;
private List<String> identifiers = new ArrayList<>();
private UserTokenDTO userToken;
}
first dto List identifiers
public class MessagetoMqDTO implements Serializable{
private Long id;
private String data;
private String device;
private String headers;
private Boolean isProcessed;
private String notification;
private String referenceCode;
private Boolean scheduled;
private Boolean transactional;
private Instant startFromTime;
private Instant expirationTime;
private String identifiers ;
private UserTokenDTO userToken;
private String clientToken;
}
second DTO
use this
#Mapping(target = "messageDTO", source = "messageDTO")
MessagetoMqDTO toDto(MessageRqDTO m,String identifier,String clientToken);
Error:
java: Can't map property "String identifiers" to "List<String> identifiers". Consider to declare/implement a mapping method: "List<String> map(String value)".
Add this method to your mapper interface:
default String mapIdentifiers(List<String> identifiers){
String identifiersSeparator = ",";
return identifiers.stream().collect(Collectors.joining(identifiersSeparator));
}
I want to know if it's possible to map a DTO to an entity class with a composite pk. I've been reading ModelMapper documentation about PropertyMap but I can't make it work.
Here is the code:
PlanDTO:
public class PlanDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String formula;
private String frequency;
private String pricingtable;
// getters and setters omitted
PlanId:
#Embeddable
public class PlanId implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
public BillingPlanId() { }
public PlanId(Long id, String name) {
this.id = id;
this.name = name;
}
// getters and setters omitted
}
Plan:
#Entity
#Table(name = "plan")
public class Plan implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private PlanId id;
#Column(name = "formula")
private String formula;
#Column(name = "frequency")
private String frequency;
#Column(name = "pricingtable")
private String pricingTable;
public Plan() { }
//setters and getters omitted
}
Here is the ModelMapper configuration.
#Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setAmbiguityIgnored(true);
PropertyMap<PlanDTO, Plan> itemMap1 = new PropertyMap<PlanDTO, Plan>() {
protected void configure() {
map().setFormula(source.getFormula());
map().setFrequency(source.getFrequency());
map().setId(new Plan(source.getId(), source.getName()));
map().setPricingTable(source.getPricingtable());
}
};
modelMapper.addMappings(itemMap1);
}
But this happens at runtime debug image
Is there something wrong with the configuration? Do I miss something?
I am not quite sure what is your problem but mapping should be quite easy with a just one property mapping:
modelMapper.addMappings(new PropertyMap<PlanDTO, Plan>() {
#Override
protected void configure() {
map().getId().setName(source.getName());
}
});
All the other fields should be implicitly mapped by their name. Even the PlanId.id.
I am not able to fetch all records from two tables using the below query
I have tried this but I am getting a result from one table only. I want a result of both the tables i.e, client_software_param_mapping and client_file_configuration having the same ClientId which is a foreign key from third pojo(client_software_configuration) to first and second pojo.
public Result showClientConfiguration() {EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultPU");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Query q=entityManager.
createQuery("SELECT c FROM client_software_param_mapping c JOIN fetch client_file_configuration f ON c.ClientId=f.ClientId");
List data =q.getResultList();
return ok(Json.toJson(data));
}
first pojo
#Entity
public class client_file_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String sourceFolder;
private String sourceFile;
private String processingFolder;
private String processingFile;
private String processedFolder;
private int intervalInMin;
private String readAfterDelay;
private String parserClass;
private String directoryMode;
private String fileMode;
private String actionMode;
private String type;
private String fileExpressionResolver;
#OneToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
secondpojo
#Entity
public class client_software_param_mapping {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String paramKey;
private String paramValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getParamKey() {
return paramKey;
}
public void setParamKey(String paramKey) {
this.paramKey = paramKey;
}
public String getParamValue() {
return paramValue;
}
public void setParamValue(String paramValue) {
this.paramValue = paramValue;
}
#ManyToOne
#JoinColumn(name = "ClientId")
private client_software_configuration clientSoftwareConfiguration;
public client_software_configuration getClientSoftwareConfiguration() {
return clientSoftwareConfiguration;
}
public void setClientSoftwareConfiguration(client_software_configuration clientSoftwareConfiguration) {
this.clientSoftwareConfiguration = clientSoftwareConfiguration;
}
}
thirdpojo
#Entity
public class client_software_configuration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String url;
private int port;
private String endPoint;
private String isPost;
private String isPing;
private String params;
private int serialNo;
private String dateFormat;
private String token;
}
this is the right query as it is returning the object of the third pojo present at that ClientId so it is able to understand the type of ClientId.JPQL never uses table and column names. It always uses entity names and their mapped fields/properties names.so here I have taken the object of the third pojo having the ClientId field.
select c,p from client_file_configuration c,client_software_param_mapping p where c.clientSoftwareConfiguration = p.clientSoftwareConfiguration
I am using realm in my project with the following model class
#Data
#Type("user")
#Builder()
#NoArgsConstructor
#AllArgsConstructor
#EqualsAndHashCode(of = {"id", "email"}, callSuper = true)
#JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)
public class User extends RealmObject {
#PrimaryKey
#Id(IntegerIdHandler.class)
private int id;
private String firstName;
private String lastName;
private String email;
#Ignore
private String password;
private boolean isAdmin;
private boolean isSuperAdmin;
private String createdAt;
private String lastAccessedAt;
private String contact;
private String deletedAt;
private String details;
private boolean isVerified;
private String thumbnailImageUrl;
private String iconImageUrl;
private String smallImageUrl;
private String avatarUrl;
private String facebookUrl;
private String twitterUrl;
private String instagramUrl;
private String googlePlusUrl;
private String originalImageUrl;
}
Most of those annotations are from lombok.
When I run my project, I get the following error
Error:(149, 20) error: realmGet$id() in org_fossasia_openevent_core_auth_model_UserRealmProxy cannot override realmGet$id() in User
return type Integer is not compatible with int
The weird part is that this error arises from realm generated code.
Any suggestions?
Here is my entity class.
#Entity
public class Store implements Serializable {
private static final long serialVersionUID = 1L;
public Store() {
}
#Id
private int id;
private String code;
private String password;
private String forgetPasswordNote;
private String key;
private String ownerId;
private String storeLink;
private String activationCode;
private String name;
private String homepageUrl;
private String sessionToken;
private Date dateCreated;
private Date expireDate;
private Date lastModified;
private String nmPassword;
private String storeType;
private String premium;
private double money;
private boolean refreshed;
private String country;
private String lang;
private String varId;
private String fbPageId;
private boolean fbEnabled;
private boolean informative;
private boolean active;
private String fbEnabledBy;
private String ipAddress;
private String comments;
private float commission;
private String picasaEmail;
// all getter and setter goes here
}
Here is my controller
#Controller
public class RegController {
#RequestMapping(value = "/create/database")
public String createDatabase(ModelMap map, HttpServletRequest request) {
Store store = new Store();
store.setId(1);
store.setCode("1");
System.out.println("test worl");
#SuppressWarnings("deprecation")
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
try {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(store);
session.getTransaction().commit();
session.close();
} catch (Exception e) {
System.out.println(e.toString());
}
return "home";
}
}
When I run the url localhost:8080/MyApp/create/database I am getting and error. org.hibernate.exception.SQLGrammarException: could not execute statement
Is there any reserved keyword on my entites class?
I have found the solution key is reserved keyword on mysql database so I simply change the key to storekey and everything work fine.