I want to retrieve 3 columns from DB.More than 2 or 3 rows are retrieved while querying.This is the query String query="select createdTime,receiptStatus,pointsEarned from Receipt where loyaltyId=:loyaltyId";
List x= (List) entityManager.createQuery(query).setParameter("loyaltyId",loyaltyId).getResultList();
I want to map the columns to a pojo class and pass the list(or use an object of that pojo).i created a pojo class like this
public class TransactionHistoryEntity
{
private List<String> tranStatus;
private List<String> tranDate;
private List<String> pointsEarned;
public List<String> getTranStatus() {
return tranStatus;
}
public void setTranStatus(List<String> tranStatus) {
this.tranStatus = tranStatus;
}
public List<String> getTranDate() {
return tranDate;
}
public void setTranDate(List<String> tranDate) {
this.tranDate = tranDate;
}
public List<String> getPointsEarned() {
return pointsEarned;
}
public void setPointsEarned(List<String> pointsEarned) {
this.pointsEarned = pointsEarned;
}
}
created time should be mapped to tranDate,receiptstatus to tranStatus,pointsEarned to pointsEarned.
How can i achieve this ?? is my query correct ?
Criteria cr= getCurrentSession().createCriteria(Receipt.class)
.add(Restrictions.eq("loyaltyId", loyaltyId))
.setProjection(Projections.projectionList()
.add(Projections.property("createdTime"), "createdTime")
.add(Projections.property("receiptStatus"), "receiptStatus")
.add(Projections.property("pointsEarned "), "pointsEarned "))
.setResultTransformer(Transformers.aliasToBean(Receipt.class));
List<Receipt> receiptList = cr.list();
This Criteria act as String query="select createdTime,receiptStatus,pointsEarned from Receipt where loyaltyId=:loyaltyId"; and map the return result to List<Receipt>
TransactionHistoryEntity trans = new TransactionHistoryEntity ();
List<String> tranStatus = new ArrayList<String>();
List<String> tranDate = new ArrayList<String>();
List<String> pointsEarned = new ArrayList<String>();
for(int i = 0 ; i < receiptList.size() ; i++){
tranDate.add(receiptList.get(i).getCreatedTime());
tranStatus.add(receiptList.get(i).getReceiptStatus());
pointsEarned.add(receiptList.get(i).getPointsEarned());
}
TransactionHistoryEntity.setTranStatus(tranStatus);
TransactionHistoryEntity.setTranDate(tranDate);
TransactionHistoryEntity.setPointsEarned(pointsEarned)
And this to map the return result to TransactionHistoryEntity
Related
I am new in Java and Spring
how to loop / get result for this
[
WhatsappContatcsDTO(whatsappid = 11111111111, name = John Dee),
WhatsappContatcsDTO(whatsappid = 16315551234, name = Kerry Fisher)
]
because i get that result from query jpa via #Query?
i do like to get result object from those result query
i like to get result here when i hit my server :
[
{ name: "John Dee", whatsappid: "11111111111"},
{ name: "Kerry Fisher", whatsappid: "16315551234"}
]
this is my service :
public List<WhatsappContactVO> allContacts() {
List<WhatsappContactVO> finalResult = new ArrayList<>();
List<WhatsappChat> resultPerKey = whatsappChatRepository.findAllContact();
for(WhatsappChat data: resultPerKey) {
WhatsappContactVO result = modelMapper.map(resultPerKey, WhatsappContactVO.class);
finalResult.add(result);
}
return finalResult;
}
Create Converter which will convert your WhatsappChat to WhatsappContactVO as below example.
#Component
public class WhatsappContactVOConvertor implements Converter<WhatsappContactVO, WhatsappChat> {
/**
* {#inheritDoc}
*/
#Override
public WhatsappContactVO convert(final WhatsappChat whatsappChat) {
final WhatsappContactVO whatsappContactVO = new WhatsappContactVO();
whatsappContactVO.setWhatsappid(whatsappChat.getwhatsappid());
whatsappContactVO.setName(whatsappChat.getName());
return whatsappContactVO;
}
}
Initialize below conversionservice.
#Autowired
private ConversionService mvcConversionService;
Required Spring classes under package
org.springframework.core.convert
Now You have to use this mvcConversionService to convert your WhatsappChat to WhatsappContactVO as per below
public List<WhatsappContactVO> allContacts() {
List<WhatsappContactVO> finalResult = new ArrayList<>();
List<WhatsappChat> resultPerKey = whatsappChatRepository.findAllContact();
finalResult = resultPerKey.stream().map(result-> mvcConversionService.convert(result, WhatsappContactVO.class))
.collect(Collectors.toList());
return finalResult;
}
Class A
{
private String name;
private String whatsappid;
}
List<WhatsappContatcsDTO> exList=dao.getInformation();
List<A> newList=exList.stream().map(e->Converter.convert(ex)).collect(Collectors.toList());
String json=DTOToJsonConverter.convertDTOToJsonString(newList);
public class DTOToJsonConverter
{
public static String convertDTOToJsonString(List<A> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
returning JSON from list of DTOs
You can use Modelmapper with TypeToken.
List<WhatsappChat> resultPerKey = whatsappChatRepository.findAllContact();
List<WhatsappContactVO> finalResult = new ArrayList<>();
finalResult = new ModelMapper()
.map(resultPerKey,new TypeToken<List<WhatsappContactVO> >(){}.getType());
I want to save/parse data from ArrayList to List but I'm not able to figure out how can I achieve it.
I have 2 Lists as below:
public static ArrayList<String> list2= new ArrayList<>();
public static List<Contact> sortedList= new ArrayList<>();
list2 is having data like
ArrayList<String> list2 = ["9847523587", "6738654738"]
I want list2 data in sortedList.
How can I get that?
Contact.java
public class Contact implements Serializable, Comparable<Contact> {
/**
*
*/
private String fullName, firstName, lastName, androidId, androidRawId, androidTagId, organization;
private transient Uri photoUri, thumbnailUri;
private List<NumberOrAddress> addresses;
private transient ArrayList<ContentProviderOperation> changesToCommit;
private transient ArrayList<ContentProviderOperation> changesToCommit2;
public void setInitial(String initial) {
this.initial = initial;
}
public Contact() {
addresses = new ArrayList<>();
androidId = null;
thumbnailUri = null;
photoUri = null;
changesToCommit = new ArrayList<>();
changesToCommit2 = new ArrayList<>();
hasSipAddress = false;
}
}
}
Added Contact.java just to show how its constructed.
You need some method which takes a String and returns a Contact in order to convert between the two different types.
If Contact has a constructor which takes a string, for example, then you can do:
list2.stream()
.map(Contact::new)
.forEach(sortedList::add);
You can do something like this(assuming contact.getContactString() returns the required string):
for(Contact contact: list1){
list2.add(contact.getContactString());
}
Collection.sort(list2);
And then:
for(String str: list2){
// assuming Contact can be constructed using a String
sortedList.add(new Contact(str));
}
I've created a DataGrid so:
DataGrid<String> grid = new DataGrid<String>();
grid.setPageSize(4);
TextColumn<String> date = new TextColumn<String>() {
public String getValue(String object) {
return object;
}
};
grid.addColumn(date, "Date");
TextColumn<String> time = new TextColumn<String>() {
public String getValue(String object) {
return object;
}
};
grid.addColumn(time, "Time");
TextColumn<String> number = new TextColumn<String>() {
public String getValue(String object) {
return object;
}
};
grid.addColumn(number, "Number");
Now I'd like to populate it but I don't understood how to do it because I have these String[] and they must be splitted also:
textString[1]="01/01/2014;10:00;300";
textString[2]="02/02/2014;11:00;400"; ...
Thanks in advance.
UPDATE
#Sturmination I followed your hint but there is another problem for this code(assuming that splitting is done):
..
protected static List<Example> EXAMPLES = null;
..
public void method() {
...
EXAMPLES = Arrays.asList(new Example("01/01/2014", "10:00", "300"));
grid.setRowCount(EXAMPLES.size(), true);
grid.setRowData(0, EXAMPLES);
..
}
It returns this error:
The method setRowData(int, List<? extends String>) in the type AbstractHasData<String> is not applicable for the arguments (int, List<Example>)
And it suggests : Change type of EXAMPLES to List<? extends String> but it doesn't work anyway.
Have you tried this:
DataGrid<String> grid = new DataGrid<String>();
grid.setPageSize(4);
TextColumn<String> date = new TextColumn<String>() {
public String getValue(String object) {
return object.split(';')[0];
}
};
grid.addColumn(date, "Date");
TextColumn<String> time = new TextColumn<String>() {
public String getValue(String object) {
return object.split(';')[1];
}
};
grid.addColumn(time, "Time");
TextColumn<String> number = new TextColumn<String>() {
public String getValue(String object) {
return object.split(';')[2];
}
};
grid.addColumn(number, "Number");
A nicer approach would be to create a new Java Bean for your rows and convert your String[] items to a List<Row> of the new row objects
You can use String[] in your code:
DataGrid<String> grid = new DataGrid<String>();
TextColumn<String[]> date = new TextColumn<String[]>() {
public String getValue(String[] object) {
return object[0];
}
};
Split your strings when you add them:
private ListDataProvider<String[]> dataProvider = new ListDataProvider<String[]>();
private List<String[]> displayItems = dataProvider.getList();
...
for (String textString : textStrings) {
displayItems.add(textString.split(";");
}
I would do it like this, if size of you data is not huge.
Create a class
Class YourClass{
private String date, time, number;
public YourClass(String date, String time, String nuber){
this.date=date;
this.time=time;
this.number=number;
}
//getters and setters here
}
Create a method to conver you values
private List<YourObject> convert(String[] values){
List<YourClass> data= new ArrayList<YourClass>();
String date, time, number;
for(i=0; values.size(); i++){
values[i] //split the string and asign values to date, time and number
dataList.add(new YourClass(date, time, number));
}
return dataList;
}
Add you values to DataGrid
ListDataProvider<YourClass> provider= new ListDataProvider<YourClass>();
List<YourClass> dataList = new ArrayList<YourClass>();
dataList.addAll(convert(textString[]));
provider.addDataDisplay(grid);
provider.setList(dataList);
Then in your Columns just:
return object.getDate();
return object.getTime();
return object.getNumber();
I have a table with has the columns namely
recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId
Now I have convert the data from above columns to the JSON object data which looks like below
{
"recordId" :10,
"recordName" : "RECORDS",
"records" : [ {
"titleField" : 1,
"titleIDMap" : null,
"titleId" : 500,
"titleStartDate" : "2013-12-22T00:00:00.000+0000",
"titleEndDate" : "2013-12-03T00:00:00.000+0000",
"languageId" : 20
}]
}
Please note that records is an array of columns ( titleFeild,titleIDMap,titleId,titleStartDate,titleEndDate,languageId)
The code so far I have developed is
List<Object[]> objList = dao.getStatus();
Integer result = null;
JSONObject jsonData = new JSONObject();
JSONArray jsonDataArray = new JSONArray();
if(objList!=null && objList.size()>10000)
{
for (Object[] nameObj : objList) {
jsonData.put("", nameObj.get(arg0) );
}
}
How do I construct the JSON Object from the columns data ?
You can easily achieve this with google-gson library. In simple terms you would have to create a couple of Pojos (with reference to another containin a list of references).
Consider RecordID and RecordName as Meta Data.
Create a pojo representing this information:
public class DbMetaPojo {
private int recordID;
private String recordName;
private List<Record> records;
public List<Record> getRecords() {
return records;
}
public void setRecords(List<Record> records) {
this.records = records;
}
public String getRecordName() {
return recordName;
}
public void setRecordName(String recordName) {
this.recordName = recordName;
}
public int getRecordID() {
return recordID;
}
public void setRecordID(int recordID) {
this.recordID = recordID;
}
}
Create another pojo with the actual Record fields:
public class Record {
public int getTitleFeild() {
return titleFeild;
}
public void setTitleFeild(int i) {
this.titleFeild = i;
}
public String getTitleIDMap() {
return titleIDMap;
}
public void setTitleIDMap(String titleIDMap) {
this.titleIDMap = titleIDMap;
}
public int getTitleId() {
return titleId;
}
public void setTitleId(int titleId) {
this.titleId = titleId;
}
public String getTitleStartDate() {
return titleStartDate;
}
public void setTitleStartDate(String titleStartDate) {
this.titleStartDate = titleStartDate;
}
public String getTitleEndDate() {
return titleEndDate;
}
public void setTitleEndDate(String titleEndDate) {
this.titleEndDate = titleEndDate;
}
public int getLanguageId() {
return languageId;
}
public void setLanguageId(int languageId) {
this.languageId = languageId;
}
private int titleFeild;
private String titleIDMap;
private int titleId;
private String titleStartDate;
private String titleEndDate;
private int languageId;
}
Now just a method to populate your POJOs with the relevant data (replace the hardcoding logic with your data retrieve):
public static void main(String... main) {
DbMetaPojo obj = new DbMetaPojo();
obj.setRecordID(10);
obj.setRecordName("RECORDS");
Record record = new Record();
record.setLanguageId(20);
record.setTitleEndDate("2013-12-22T00:00:00.000+0000");
record.setTitleFeild(1);
record.setTitleId(500);
record.setTitleIDMap("SOME NULL");
record.setTitleStartDate("2013-12-22T00:00:00.000+0000");
List<Record> list = new ArrayList<Record>();
list.add(record);
obj.setRecords(list);
Gson gson = new Gson();
String json = gson.toJson(obj);
System.out.println(json);
}
Output is your formed JSON:
{
"recordID": 10,
"recordName": "RECORDS",
"records": [
{
"titleFeild": 1,
"titleIDMap": "SOME NULL",
"titleId": 500,
"titleStartDate": "2013-12-22T00:00:00.000+0000",
"titleEndDate": "2013-12-22T00:00:00.000+0000",
"languageId": 20
}
]
}
EDIT:
To align to your code, you might want to do something like:
List<Object> objList = dao.getStatus();
List<DbMetaPojo> metaList = new ArrayList<DbMetaPojo> ();
if (objList != null && objList.size() > 10000) {
for (Object nameObj : objList) {
DbMetaPojo meta = new DbMetaPojo();
meta.setRecordID(nameObj[0]);
meta.setRecordName(nameObj[0]);
...
...
...
metaList.add(meta);
}
}
First of all what you have to do is retrieve the data from the columns of the table using your DAO and calling a Function from DAOIMPL which in turn will return the list of data(POJO probably).
Create a map like this which will contain your key value pair for example recordid and value,
recordname and value
Map<String,Object> objMap = new HashMap<String,Object>();
objMap.put("recordId", Record.getId());
objMap.put("recordName",Record.getName());
// Now here is the deal create another hashmap here whose key will be records "the key for your second array"
//Put the values in this second hashmap as instructed above and put it as a key value pair.
........
.......
.......
JSONObject JsonObject = JSONObject.fromObject(objMap);//This will create JSON object out of your hashmap.
objJSONList.add(JsonObject);
}
StringBuffer jsonBuffer = new StringBuffer();
jsonBuffer.append("{\"data\": {");
jsonBuffer.append(objJSONList.tostring());
jsonBuffer.append("}");
//jsonBuffer.append(",\"total\":"+ objJSONList.size());// TOTAL Optional
//jsonBuffer.append(",\"success\":true}");//SUCCESS message if using in callback Optional
Create an object which has your attribues. (recordID, recordName , titleFeild, titleIDMap, titleId, titleStartDate, titleEndDate, languageId)
Get data from dao and convert it to json. It will looks like what you want.
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
I think your dao.getStatus() should return a List with Map keys and values. Your key would be column name and value would be content.
List<Map<String,Object>> objList = dao.getStatus();
if(objList!=null && objList.size()>10000){
for(Map<String,Object> row : objList) {
Iterator<String> keyList = row.keySet().iterator();
while(keyList.hasNext()){
String key = keyList.next();
jsonData.put(key, row.get(key));
}
}
}
For the records array you need to build it while iterating table columns.
Combining above code with building records array would be something like this..
String[] group = {"titleField","titleIDMap","titleId","titleStartDate","titleEndDate","languageId"};
List<String> recordGroup = Arrays.asList(group);
Map<Object, JSONArray> records = new HashMap<Object,JSONArray>();
List<Map<String,Object>> objList = dao.getStatus();
JSONObject jsonData = new JSONObject();
if(objList!=null && objList.size()>10000){
for(Map<String,Object> row : objList) {
int columnCount = 0;
Iterator<String> keyList = row.keySet().iterator();
while(keyList.hasNext()){
String key = keyList.next();
if(recordGroup.contains(key)){
Object recordId = row.get("recordId");
JSONArray recordArray = new JSONArray();
if(records.containsKey(recordId)){
recordArray = records.get(recordId);
JSONObject jsonObj = null;
if(columnCount >= recordGroup.size()){
jsonObj = new JSONObject();
recordarray.add(jsonObj);
columnCount = 0;
}
else {
jsonObj = (JSONObject) recordArray.get(recordArray.size()-1);
}
jsonObj.put(key, row.get(key));
columnCount++;
}
else {
JSONObject jsonObj = new JSONObject();
jsonObj.put(key, row.get(key));
recordArray.add(jsonObj);
records.put(recordId, recordArray);
}
jsonData.put("records", records.get(recordId));
}
else {
jsonData.put(key, row.get(key));
}
}
}
}
I wanted to create a table/list in Java, and I wonder what is the best way to handle it.
The table should have a structure like this:
Term propertyList entitiesList
a1 p1=1, p2=2, p3=2 T1,T2
a2 p5=0, p4=5 ,p3=3 T2,T1
a3 p1=1 ,p4=3, p3=9 T3,T1,T2
...
a10
I have a list with exactly 10 terms, and for every term there is a list of properties (deep with key and value), and the properties can be either in one or more entities.
I need some help on how to create it, e.g. should I use list, map, collection etc.
How can I add hardcoded values to them as literals in the code, and what is the best way to read data from it, taking into account performance, given that later I will need to use this for every entity and find the related properties that participate in every term.
first off Create Term class.
So you have list of Terms: List<Term>
Term class
public class Term {
private String mName = "";
private Map<String, Integer> mPropertyMap = new LinkedHashMap<String, Integer>();
private List<String> mEntitiesList = new ArrayList<String>();
public Term(String name) {
mName = name;
}
public void generate(Map<String, Integer> propertyMap, List<String> entitiesList) {
mPropertyMap = propertyMap;
mEntitiesList = entitiesList;
}
public Map<String, Integer> getPropertyMap() {
return mPropertyMap;
}
public void setPropertyMap(Map<String, Integer> propertyMap) {
this.mPropertyMap = propertyMap;
}
public List<String> getEntitiesList() {
return mEntitiesList;
}
public void setEntitiesList(List<String> entitiesList) {
this.mEntitiesList = entitiesList;
}
public String getName() {
return mName;
}
public void setmName(String name) {
this.mName = name;
}
}
Main Class
public class MyClass {
private List<Term> mTermList = null;
private void init() {
mTermList = new ArrayList<Term>();
}
private void addSomeTerm() {
Map<String, Integer> propertyMap = new LinkedHashMap<String, Integer>();
propertyMap.put("p1", 1);
propertyMap.put("p2", 2);
propertyMap.put("p3", 3);
List<String> entitiesList = new ArrayList<String>();
entitiesList.add("T1");
entitiesList.add("T2");
Term term = new Term("a1");
term.generate(propertyMap, entitiesList);
mTermList.add(term);
}
private String printTerms() {
StringBuilder buff = new StringBuilder();
for(Term currTerm : mTermList){
buff.append(currTerm.getName()).append(" ");
Map<String, Integer> propertyMap = currTerm.getPropertyMap();
Set<String> sets = propertyMap.keySet();
Iterator<String> itr = sets.iterator();
String key = null;
Integer value = null;
while(itr.hasNext()){
key = itr.next();
value = propertyMap.get(key);
buff.append(key + "=" + value).append(",");
}
buff.setLength(buff.length()-1); // remove last ','
buff.append(" ");
List<String> entitiesList = currTerm.getEntitiesList();
for(String str : entitiesList){
buff.append(str).append(",");
}
buff.setLength(buff.length()-1); // remove last ','
}
return buff.toString();
}
/**
* #param args
*/
public static void main(String[] args) {
MyClass m = new MyClass();
m.init();
m.addSomeTerm();
System.out.println(m.printTerms());
}
}
Output:
a1 p1=1,p2=2,p3=3 T1,T2
It looks like you could have the following structure:
class Term {
String id;
Map<String, String> properties;
List<Entity> entities; // (or Set<Entity> if no duplicates are allowed)
}
But it's not very clear what you mean by "deep" and by "the properties can be either in one or more entities".