Could someone help me out ow to get data from a table in the database by sending a list.
`
List<CampaignStructure> campIdList = new ArrayList<>(); try {
JSONArray clientjson = new JSONArray(campaignids);
Set<Long> list = new HashSet<>();
for(int i = 0; i < clientjson.length(); i++){
list.add(Long.parseLong(clientjson.getJSONObject(i).getString("id")));
}
for(Long id: list){
CampaignStructure c = new CampaignStructure();
c.setCampaignId(id);
campIdList.add(c);
}
} catch (JSONException e) {
}
Here campaignids contains list of ids (can contain duplicates).
campIdList contains distinct ids. i want to send these ids and get the data from database.
findByCampaignIdIn(List campIdList) should work.
You can find all list of JPA repository keywords can be found in the current documentation listing.
It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.
Related
i am getiing proper values from DB but Getting Duplicate List Values while add list object to class object, in Spring Boot
Please suggest to me how to do it.
Get data from DB Code : Here Rooms is my DB Entity class
CriteriaBuilder roomsBuilder = roomSession.getCriteriaBuilder();
CriteriaQuery<Rooms> query = roomsBuilder.createQuery(Rooms.class);
Root<Rooms> root = query.from(Rooms.class);
Predicate userRestriction = roomsBuilder.or(roomsBuilder.notEqual(root.get(SmatrEntityParameters.IS_DELETED), "Y"),
roomsBuilder.isNull(root.get(SmatrEntityParameters.IS_DELETED)));
Predicate userRestriction2 = roomsBuilder.and(roomsBuilder.equal(root.join("properties").get(SmatrEntityParameters.PROPERTY_ID), propertyId));
query.where(roomsBuilder.and(userRestriction, userRestriction2));
Query q = roomSession.createQuery(query);
List<Rooms> getroomslistobj= q.getResultList();
Iterate the list code: Here getAllRoomsobj means main response pojo class
List<GetAllRooms> getallroomslistobj = new ArrayList<GetAllRooms>();
for (int i = 0; i < getroomslistobj.size(); i++) {
int dbroomId = getroomslistobj.get(i).getRoomId();
String dbroomName = getroomslistobj.get(i).getRoomName();
// Actual code start
getAllRoomsobj.setRoomId(dbroomId);
getAllRoomsobj.setRoomName(dbroomName);
getallroomslistobj.add(getAllRoomsobj);
// Actual code end
}
I tried one code at the middle of the Actual code but I did not want create a new object for the response class:
GetAllRooms object = new GetAllRooms();
object.setRoomId(dbroomId);
object.setRoomName(dbroomName);
getallroomslistobj.add(object);
Please Help me Out,
Thanks in Advance
u can try it by stream.map() of java8
I'm sorry this question header is not 100% correct. Because of that, I'll explain my scenario here.
I created a function to merge 4 data sets into one return format. Because that's the format front-end side needed. So this is working fine now.
public ReturnFormat makeThribleLineChart(List<NameCountModel> totalCount, List<NameCountModel>,p1Count, List<NameCountModel> p2Count, List<NameCountModel> average) {
ReturnFormat returnFormat = new ReturnFormat(null,null);
try {
String[] totalData = new String[totalCount.size()];
String[] p1Data = new String[p1Count.size()];
String[] p2Data = new String[p2Count.size()];
String[] averageData = new String[p2Count.size()];
String[] lableList = new String[totalCount.size()];
for (int x = 0; x < totalCount.size(); x++) {
totalData[x] = totalCount.get(x).getCount();
p1Data[x] = p1Count.get(x).getCount();
p2Data[x] = p2Count.get(x).getCount();
averageData[x] = average.get(x).getCount();
lableList[x] = totalCount.get(x).getName();
}
FormatHelper<String[]> totalFormatHelper= new FormatHelper<String[]>();
totalFormatHelper.setData(totalData);
totalFormatHelper.setType("line");
totalFormatHelper.setLabel("Uudet");
totalFormatHelper.setyAxisID("y-axis-1");
FormatHelper<String[]> p1FormatHelper= new FormatHelper<String[]>();
p1FormatHelper.setData(p1Data);
p1FormatHelper.setType("line");
p1FormatHelper.setLabel("P1 päivystykseen heti");
FormatHelper<String[]> p2FormatHelper= new FormatHelper<String[]>();
p2FormatHelper.setData(p2Data);
p2FormatHelper.setType("line");
p2FormatHelper.setLabel("P2 päivystykseen muttei yöllä");
FormatHelper<String[]> averageFormatHelper= new FormatHelper<String[]>();
averageFormatHelper.setData(averageData);
averageFormatHelper.setType("line");
averageFormatHelper.setLabel("Jonotusaika keskiarvo");
averageFormatHelper.setyAxisID("y-axis-2");
List<FormatHelper<String[]>> formatHelpObj = new ArrayList<FormatHelper<String[]>>();
formatHelpObj.add(totalFormatHelper);
formatHelpObj.add(p1FormatHelper);
formatHelpObj.add(p2FormatHelper);
formatHelpObj.add(averageFormatHelper);
returnFormat.setData(formatHelpObj);
returnFormat.setLabels(lableList);
returnFormat.setMessage(Messages.Success);
returnFormat.setStatus(ReturnFormat.Status.SUCCESS);
} catch (Exception e) {
returnFormat.setData(null);
returnFormat.setMessage(Messages.InternalServerError);
returnFormat.setStatus(ReturnFormat.Status.ERROR);
}
return returnFormat;
}
so, as you can see here, all the formatting is hardcoded. So my question is how to automate this code for list count. Let's assume next time I have to create chart formatting for five datasets. So I have to create another function to it. That's the thing I want to reduce. So I hope you can understand my question.
Thank you.
You're trying to solve the more general problem of composing a result object (in this case ReturnFormat) based on dynamic information. In addition, there's some metadata being setup along with each dataset - the type, label, etc. In the example that you've posted, you've hardcoded the relationship between a dataset and this metadata, but you'd need some way to establish this relationship for data dynamically if you have a variable number of parameters here.
Therefore, you have a couple of options:
Make makeThribleLineChart a varargs method to accept a variable number of parameters representing your data. Now you have the problem of associating metadata with your parameters - best option is probably to wrap the data and metadata together in some new object that is provided as each param of makeThribleLineChart.
So you'll end up with a signature that looks a bit like ReturnFormat makeThribleLineChart(DataMetadataWrapper... allDatasets), where DataMetadataWrapper contains everything required to build one FormatHelper instance.
Use a builder pattern, similar to the collection builders in guava, for example something like so:
class ThribbleLineChartBuilder {
List<FormatHelper<String[]>> formatHelpObj = new ArrayList<>();
ThribbleLineChartBuilder addDataSet(String describeType, String label, String yAxisId, List<NameCountModel> data) {
String[] dataArray = ... ; // build your array of data
FormatHelper<String[]> formatHelper = new FormatHelper<String[]>();
formatHelper.setData(dataArray);
formatHelper.setType(describeType);
... // set any other parameters that the FormatHelper requires here
formatHelpObj.add(formatHelper);
return this;
}
ReturnFormat build() {
ReturnFormat returnFormat = new ReturnFormat(null, null);
returnFormat.setData(this.formatHelpObj);
... // setup any other fields you need in ReturnFormat
return returnFormat;
}
}
// usage:
new ThribbleLineChartBuilder()
.addDataSet("line", "Uudet", "y-axis-1", totalCount)
.addDataSet("line", "P1 päivystykseen heti", null, p1Count)
... // setup your other data sources
.build()
I have two lists of type List<A> and List<B>. Now, what I'm trying to do is to create a List<C>, the values of which would be read from other two lists. I tried and implemented something like this.
public void fileUpload(int customerId) throws SQLException, IOException {
myList = myTiedosto.getFileDetails(customerId);
attachmentDetails = myAttachment.getAttachmentDetails(customerId);
List<Upload> uploadList = new ArrayList<>();
for (Attachment attachment : attachmentDetails) {
Upload upload = new Upload();
upload.setUuid(attachment.getUuid());
for (Tiedosto tiedosto : myList) {
upload.setCustomerId(tiedosto.getCustomerId());
upload.setFileName(tiedosto.getFileName());
upload.setFileSize(tiedosto.getFileSize());
upload.setContent(tiedosto.getContent());
}
uploadList.add(upload);
}
for (Upload myUploadList : uploadList) {
System.out.println(myUploadList.getCustomerId()+" " +myUploadList.getFileName()+" "+myUploadList.getUuid()+" "+myUploadList.getFileSize());
}
}
When I run this, myUploadList returns the same entry twice.
output
I'm a newbie in Java, I'd really appreciate some help.
Based on your comment, you should create and add the Upload instance to the output List inside the inner loop:
for (Attachment attachment : attachmentDetails) {
for (Tiedosto tiedosto : myList) {
Upload upload = new Upload();
upload.setUuid(attachment.getUuid());
upload.setCustomerId(tiedosto.getCustomerId());
upload.setFileName(tiedosto.getFileName());
upload.setFileSize(tiedosto.getFileSize());
upload.setContent(tiedosto.getContent());
uploadList.add(upload);
}
}
This will create an Upload instance from each pair of Attachment and Tiedosto.
EDIT:
Based on your latest comment, it would be better to use traditional for loop, since you want to create an Upload instance from each pair of Attachment and Tiedosto instances having the same index:
for (int i = 0 ; i < attachmentDetails.size(); i++) {
Tiedosto tiedosto = myList.get(i);
Upload upload = new Upload();
upload.setUuid(attachmentDetails.get(i).getUuid());
upload.setCustomerId(tiedosto.getCustomerId());
upload.setFileName(tiedosto.getFileName());
upload.setFileSize(tiedosto.getFileSize());
upload.setContent(tiedosto.getContent());
uploadList.add(upload);
}
After reading your comments, I think this is what you want.
int i = 0;
for (Attachment attachment : attachmentDetails) {
Upload upload = new Upload();
upload.setUuid(attachment.getUuid());
upload.setCustomerId(myList.get(i).getCustomerId());
upload.setFileName(myList.get(i).getFileName());
upload.setFileSize(myList.get(i).getFileSize());
upload.setContent(myList.get(i).getContent());
uploadList.add(upload);
i++;
}
or if you have a way of identifying which if the myList belongs to which attachment then you can loop through the myList and do a check:
for (Attachment attachment : attachmentDetails) {
Upload upload = new Upload();
upload.setUuid(attachment.getUuid());
for (Tiedosto tiedosto : myList) {
if(tiedosto.getCustomerId() == attachment.getId()//assuming you have this field
upload.setCustomerId(tiedosto.getCustomerId());
upload.setFileName(tiedosto.getFileName());
upload.setFileSize(tiedosto.getFileSize());
upload.setContent(tiedosto.getContent());
}
uploadList.add(upload);
}
The entries are not same as both have different UUID. The other details such as CustomerId,Filename, Filesize etc. are same as you are iterating the same myList for each iteration row of the list myAttachment. So, verify whether you are iterating correct with respect to the expected data
Man, It's a logical problem in your program.
I guess it's caused by the inner cycle.
It's overwriting the upload with the last element myList's information. Maybe that's why you have exactly the same information in all the fields, except for the uuid.
We use the TFS Java API to fetch WorkItems from a TFS server:
TFSTeamProjectCollection collection = TFSTeamProjectCollectionUtils
.openTeamProjectCollection(serverUrl, credentials,
new DefaultConnectionAdvisor(Locale.getDefault(),
TimeZone.getDefault()));
WorkItemClient client = collection.getWorkItemClient();
List<WorkItem> result = new ArrayList<>();
try {
WorkItemCollection workItems = client.query(wiqlQuery, null, false);
for (int i = 0; i < workItems.size(); i++) {
WorkItem item = workItems.getWorkItem(i);
result.add(item);
}
return result;
} catch (TECoreException e) {
throw new ConQATException("Failed to fetch work items from TFS", e);
}
If I run the query select * from workitems I get all workitems on the server with all fields and all links. Since I'm only interested in some of the fields, I would like to restrict the query to only those and save some bandwidth/time: select ID, Title from workitems
This works fine, but now the links of the items are missing (i.e. item.getLinks() always returns an empty collection).
Is there a way to select the links other than select * from workitems?
After some more digging around, I found that you can create a link query and run it like this:
WorkItemLinkInfo[] infos = client.createQuery("select * from workitemlinks").runLinkQuery()
With this, you can get the links as WorkItemLinkInfo objects that contain the IDs of the target and source node and the link type.
The solution using WorkItemLinkInfo is correct.
Just as remark: Using a WIQL Query you only receive the attributes you were querying - which cannot be the set of links of a work item (therefore always empty). If you query a single workitem using
WorkItemClient client = TFSConnection.getClient();
WorkItem firstWorkItem = client.getWorkItemByID(id);
then you also get the LinkCollection using (containing RelatedLinks, ExternalLinks or HyperLinks)
LinkCollection linkcoll = firstWorkItem.getLinks()
I'm trying to grab a list of snapshots from our Storage Gateway and put them into a JTable. However, when I use the AWS Java API to retrieve a list of snapshots, I only am able to retrieve what appears to be the public snapshots published by Amazon. When I set the DescribeSnapshotsRequest.setOwnerIds() to include "self", the list is empty.
Here is the offending code:
private void createTable() {
Object[][] data = null;
String[] columns = new String[]{"Snapshot ID", "Owner ID", "Snapshot Date"};
DescribeSnapshotsRequest req = new DescribeSnapshotsRequest();
req.setOwnerIds(Arrays.<String>asList("self"));
try {
snapshots = ec2Client.describeSnapshots(req).getSnapshots();
data = new Object[snapshots.size()][3];
int i = 0;
for(Snapshot item : snapshots) {
data[i][0] = item.getSnapshotId();
data[i][1] = item.getOwnerId();
data[i][2] = item.getStartTime();
i++;
}
} catch(Exception e) {
System.out.println("Invalid Credentials!");
}
table = new JTable(data, columns);
table.setAutoCreateRowSorter(true);
}
The List snapshots is empty unless I either remove the DescribeSnapshotsRequest, or set the owner ID to "amazon".
Long story short, why can't I access my private snapshots from the Storage Gateway?
Figured it out. Turns out you have to explicitly define the EC2 endpoint. Somehow I missed that step.
Here is the list of endpoints:
http://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region
AmazonEC2Client.setEndpoint("<Endpoint URL>");