Update multiple rows using single query in JDO - sql

Iam having a table like this
SorOrder Name Date
1 Image1 5/6/15
2 Image2 6/8/16
3 Image3 6/8/16
4 Image4 9/8/16
..........
Now if iam deleting image2 i want to udate the table so that the sortorder
again is in ordered form like this
Updated Table :
SorOrder Name Date
1 Image1 5/6/15
2 Image3 6/8/16
3 Image4 9/8/16
..........
SO how to make it posible??
This is the class for the table Images:
public class Images extends ApplicationEntity{
#Column(name="PROFILE_ID", allowsNull="false")
private Profile profile;
private int sortOrder;
private boolean active;
private Date deletedDate;
public Images (){
super.setEntity("Images ");
}
public Images (Profile profile, int sortOrder, boolean active,
Date deletedDate) {
super();
this.profile = profile;
this.sortOrder = sortOrder;
this.active = active;
this.deletedDate = deletedDate;
}
public Profile getProfile() {
return profile;
}
public int getSortOrder() {
return sortOrder;
}
public void setSortOrder(int sortOrder) {
this.sortOrder = sortOrder;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getDeletedDate() {
return deletedDate;
}
public void setDeletedDate(Date deletedDate) {
this.deletedDate = deletedDate;
}
#Override
public String toString() {
return "Images [profile=" + profile + ", sortOrder=" + sortOrder
+ ", active=" + active + ", deletedDate=" + deletedDate + "]";
}
}
I tried this query: String query = "update Images set SORTORDER =((SELECT selected_value FROM (SELECT MAX(SORTORDER) AS selected_value FROM Images where ACTIVE = 0 && PROFILE_Id="+profileId+") AS sub_selected_value) + 1) where PROFILE_Id="+profileId;
But it updates all the sorOrder to same value.
I was using this code to update the sortorder:
int sortoder=1;
for (Images file : imagesListFromDB) {
file.setSortOrder(sortOrder);
sortOrder++;
}
But it takes more time,if iam having 8000 images then its really slow.SO i thought of updating in a single query. But not getting any idea

To do in a single statement you could make use of SQL. Here are a couple of ideas (adapt to your use-case) - you use the "?" parameter to set the position above what you delete.
UPDATE IMAGES SET SORTORDER =
(CASE WHEN (SORTORDER <= ?) THEN SORTORDER
ELSE (SORTORDER-1) END)
Or
UPDATE IMAGES SET SORTORDER = SORTORDER-1
WHERE SORTORDER > ?
Using DataNucleus JDOQL UPDATE extension you could do this (and set the parameter "param" to the sortOrder start point to update
pm.newQuery("UPDATE mydomain.Images SET this.sortOrder=this.sortOrder-1 WHERE this.sortOrder > :param");

Related

I get the following error when I add paging "IQueryable doesn't implement IAsyncQueryProvider" [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to implement paging for MVC .NetCore application. I have a list " List<_Item> Items which i got from azure blob" I get the following error when I add paging "IQueryable doesn't implement IAsyncQueryProvider"
Paging I'm trying to Implement:
https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page?view=aspnetcore-3.1
Possible solutions I tried looking at:
https://github.com/romantitov/MockQueryable
HomeController: Index function
[Obsolete]
public async Task<IActionResult> Index(string outletId, string contractId, string sort, string currentFilter, int? pageNumber)
{
ViewData["CurrentSort"] = sort;
ViewData["OutletId"] = String.IsNullOrEmpty(sort) ? "descending outletId" : "";
ViewData["ContractId"] = sort == "ContractId" ? "descending contractId" : "ContractId";
if (outletId != null || contractId != null)
{
pageNumber = 1;
}
else
{
outletId = currentFilter;
contractId = currentFilter;
}
blobServices.Add_Tags_on_Blob("GSS_EDM_WorkHistoryTerminationsEngagementsIRP5Request_Dev.csv");
// List<_Item> Items = (List<_Item>)blobServices.Get_BlobItem_List();
List<_Item> Items = (List<_Item>)blobServices.Find_Blob_By_Tag(outletId, contractId);
var records = Items.AsQueryable();
switch (sort)
{
case "descending outletId":
records = records.OrderByDescending(x => x.OutletId);
break;
case "descending contractId":
records = records.OrderByDescending(x => x.ContractId);
break;
case "ContractId":
records = records.OrderBy(x => x.ContractId);
break;
default:
records = records.OrderBy(x => x.OutletId);
break;
}
int pageSize = 3;
return View(await PaginatedList<_Item>.CreateAsync(records, pageNumber ?? 1, pageSize));
// return View(Items.ToPagedList(pageNumber ?? 1, 10));
}
Paging Class[Lines of code with error HomeController
1
Lines of code with error; Pagging Class
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
According to the error message, we could find The provider for the source IQueryable doesn't implement IAsyncQueryProvider. Only providers that implement IAsyncQueryProvider can be used for Entity Framework asynchronous operations..
We couldn't let List<T>.AsQueryable() to use ToListAsync method, since it doesn't implement the IAsyncQueryProvider.
To solve this issue, you could modify the PaginatedList method's CreateAsync method like below:
public static PaginatedList<T> Create(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = source.Count();
var items = source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
Usage:
return View( PaginatedList<_Item>.Create(records, pageNumber ?? 1, pageSize));

MediaStore select query returns only one row

I'm trying to develop music player, I've made a loader and adapter for my data retreiving from mediastore, but when I call query from my app it only returns one row, I don't know wat's wrong with my code, would u help me fixing that problem?
That's my loader which should return a list I'll use in another place
public static List<Song> getAllArtistSongs(Context context, long artist_id){
List<Song> ArtistSongList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{
"_id",
"title",
"album_id",
"album",
"artist",
"duration",
"track"
};
String sortorder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
String selection = "is_music=1 and artist_id="+artist_id;
Cursor cursor = context.getContentResolver().query(uri, projection, selection, null, sortorder);
assert cursor != null;
if (cursor.moveToFirst()) {
do {
int trackNumber = cursor.getInt(6);
while (trackNumber >= 1000) {
trackNumber -= 1000;
}
Long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
Long albumid = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
String albumname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
String artistname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
ArtistSongList.add(new Song(id, title, albumid, albumname, artist_id, artistname, duration, trackNumber));
} while (cursor.moveToNext());
cursor.close();
}
return ArtistSongList;
}
And this is the adapter which I use to bind to a recyclerview
public void onBindViewHolder(#NonNull VH holder, int position) {
Song song = artistSongList.get(position);
if(song!=null){
holder.ttv.setText(song.title);
holder.dtv.setText(song.artistName);
int trackN = song.trackNumber;
if(trackN==0){
holder.ntv.setText("_");
}else holder.ntv.setText(String.valueOf(trackN));
}
}
And this is where I call the query func
private void setupAlbumList() {
System.out.println(artistId);
songList = ArtistSongLoader.getAllArtistSongs(getActivity(), artistId);
adapter = new ArtistSongAdapter(getActivity(), songList);
recy.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
recy.setAdapter(new ArtistSongAdapter(getActivity(), songList));
}
Thx in advance for helping
My example to retrieve all tracks:
private final String track_id = MediaStore.Audio.Media._ID;
private final String track_no = MediaStore.Audio.Media.TRACK;
private final String track_name = MediaStore.Audio.Media.TITLE;
private final String artist = MediaStore.Audio.Media.ARTIST;
private final String artist_id = MediaStore.Audio.Media.ARTIST_ID;
private final String duration = MediaStore.Audio.Media.DURATION;
private final String album = MediaStore.Audio.Media.ALBUM;
private final String composer = MediaStore.Audio.Media.COMPOSER;
private final String year = MediaStore.Audio.Media.YEAR;
private final String path = MediaStore.Audio.Media.DATA;
private final String date_added = MediaStore.Audio.Media.DATE_ADDED;
public Cursor getAllTracks(Context context) {
// gets all tracks
if (context != null) {
ContentResolver cr = context.getContentResolver();
final String[] columns = {track_id, track_no, artist, track_name,
album, duration, path, year, composer};
return cr.query(uri, columns, null, null, null);
} else {
return null;
}
}
then you have
String selection = "is_music=1"
first, you do not need is_music=1. For multiple tracks you of course need more than 1 track by the same artist
The adapter is irrelevant, the query does the selection
To return albums for an artist
public Cursor getArtistsAlbumcursor(Context context, String artistId) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String artistid = MediaStore.Audio.Media.ARTIST_ID;
final String[] columns = {_id, album_id, artistid};
if (artistId != null) {
String where = artistid + " =?";
String[] aId = {artistId};
return cr.query(uri, columns, where, aId, null);
} else {
return null;
}
}

How are order line items exposed?

In the restbucks project, an order has a private list of line items. I can't figure out how this field is exposed via rest api when getting a single order. It has no public getter or anything. Is it the mixins?
#Data, #NoArgsConstructor, #AllArgsConstructor, #EqualsAndHashCode are Lombok annotations, that are used to auto-generate a boilerplate code.
#Data
#Entity
#NoArgsConstructor(force = true)
#AllArgsConstructor
#EqualsAndHashCode(callSuper = false)
public class LineItem extends AbstractEntity {
private final String name;
private final int quantity;
private final Milk milk;
private final Size size;
private final MonetaryAmount price;
public LineItem(String name, MonetaryAmount price) {
this(name, 1, Milk.SEMI, Size.LARGE, price);
}
}
You can compare this code with delomboked one (welcome to Lombok-funs club )):
#Entity
public class LineItem extends AbstractEntity {
private final String name;
private final int quantity;
private final Milk milk;
private final Size size;
private final MonetaryAmount price;
public LineItem(String name, MonetaryAmount price) {
this(name, 1, Milk.SEMI, Size.LARGE, price);
}
public LineItem(String name, int quantity, Milk milk, Size size, MonetaryAmount price) {
this.name = name;
this.quantity = quantity;
this.milk = milk;
this.size = size;
this.price = price;
}
public LineItem() {
this.name = null;
this.quantity = 0;
this.milk = null;
this.size = null;
this.price = null;
}
public String getName() {
return this.name;
}
public int getQuantity() {
return this.quantity;
}
public Milk getMilk() {
return this.milk;
}
public Size getSize() {
return this.size;
}
public MonetaryAmount getPrice() {
return this.price;
}
public String toString() {
return "LineItem(name=" + this.getName() + ", quantity=" + this.getQuantity() + ", milk=" + this.getMilk() + ", size=" + this.getSize() + ", price=" + this.getPrice() + ")";
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof LineItem)) return false;
final LineItem other = (LineItem) o;
if (!other.canEqual((Object) this)) return false;
final Object this$name = this.getName();
final Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
if (this.getQuantity() != other.getQuantity()) return false;
final Object this$milk = this.getMilk();
final Object other$milk = other.getMilk();
if (this$milk == null ? other$milk != null : !this$milk.equals(other$milk)) return false;
final Object this$size = this.getSize();
final Object other$size = other.getSize();
if (this$size == null ? other$size != null : !this$size.equals(other$size)) return false;
final Object this$price = this.getPrice();
final Object other$price = other.getPrice();
if (this$price == null ? other$price != null : !this$price.equals(other$price)) return false;
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
result = result * PRIME + this.getQuantity();
final Object $milk = this.getMilk();
result = result * PRIME + ($milk == null ? 43 : $milk.hashCode());
final Object $size = this.getSize();
result = result * PRIME + ($size == null ? 43 : $size.hashCode());
final Object $price = this.getPrice();
result = result * PRIME + ($price == null ? 43 : $price.hashCode());
return result;
}
protected boolean canEqual(Object other) {
return other instanceof LineItem;
}
}

datediff with case statement in select query linq

select case statement in linq query.
Here is the query on sql:
select case when DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101)) = 0 then
Sum([Order].OrderSubtotal)
else
case when (DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30) = 0 then Sum([Order].OrderSubtotal) else
Sum([Order].OrderSubtotal)/
(DATEDIFF(day,convert(varchar,Min([Order].CreatedOnUtc),101),convert(varchar,Max([Order].CreatedOnUtc),101))/30)
end
end as 'Account Value' from [order] where And Account.ID = #Act_ID
I am trying the code here:
var query = _orderRepository.Table;
query = query.Where(o => o.AccountId == accountId);
In query i am getting my value.
After query statement what should i write??
how do i write for case statement using linq???
#Manoj, may be the below code helps you. This sample C# project may solve the problem you have.
using System;
using System.Collections.Generic;
using System.Linq;
namespace DateDiffIssue
{
class Program
{
static void Main(string[] args)
{
// Preparing data
var data = new Order[] {
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 10:00"), OrderSubtotal = 100 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 12:00"), OrderSubtotal = 150 },
new Order { AccountID = 1, CreatedOnUtc = DateTime.Parse("1.01.2017 14:00"), OrderSubtotal = 150 }
};
// Selection
var selected = (from item in data
let accountData = data.Where(w => w.AccountID == 1)
let minDate = accountData.Min(m => m.CreatedOnUtc).Date
let maxDate = accountData.Where(w => w.AccountID == 1).Max(m => m.CreatedOnUtc).Date
let isSameDate = minDate == maxDate
let basedOn30Days = (maxDate - minDate).TotalDays / 30
let isInside30Days = (int)basedOn30Days == 0
let accountDataSum = accountData.Sum(s => s.OrderSubtotal)
select new
{
AccountValue = isSameDate ? accountDataSum :
isInside30Days ? accountDataSum :
accountDataSum / basedOn30Days
}).Distinct();
// Print each order
selected.ToList().ForEach(Console.WriteLine);
// Wait for key
Console.WriteLine("Please press key");
Console.ReadKey();
}
}
internal class Order
{
public int AccountID { get; set; }
public DateTime CreatedOnUtc { get; set; }
public int OrderSubtotal { get; set; }
}
}

LinqPad Predicatebuider Expression call not working

I am trying to get the examples working found at http://www.albahari.com/nutshell/predicatebuilder.aspx
I have the following code:
public partial class PriceList
{
public string Name { get; set; }
public string Desc {get;set;}
public DateTime? ValidFrom {get;set;}
public DateTime? ValidTo{get;set;}
public static Expression> IsCurrent()
{
return p => (p.ValidFrom == null || p.ValidFrom <= DateTime.Now) && (p.ValidTo == null || p.ValidTo >= DateTime.Now);
}
}
void Main()
{
List plList = new List()
{
new PriceList(){ Name="Billy", Desc="Skilled", ValidFrom = DateTime.Now.AddDays(-10.0) , ValidTo= DateTime.Now.AddDays(1.0) },
new PriceList(){ Name="Jamie", Desc="Quick Study",ValidFrom =DateTime.Now.AddDays(-10.0) , ValidTo= DateTime.Now.AddDays(1.0) },
new PriceList(){Name= "Larry", Desc= "Rookie",ValidFrom = DateTime.Now.AddDays(-10.0) , ValidTo= DateTime.Now.AddDays(1.0) }
};
// Method 1
var myResultList = plList.Where ( p => (p.ValidFrom == null || p.ValidFrom <= DateTime.Now)
&& (p.ValidTo == null || p.ValidTo >= DateTime.Now)).Dump();
// Method 2
plList.Where(PriceList.IsCurrent()).Dump(); // This does not work currently
}
My question is between method 1 and method 2, this IsCurrent() method does not work the functionality of the code is identical, but when I call the Method 2 PriceList.IsCurrent() I get the following error.
Any Suggestions would be greatly appreciated.
'System.Collections.Generic.List' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments
Instance argument: cannot convert from 'System.Collections.Generic.List' to 'System.Linq.IQueryable'
Try
plList.AsQueryable().Where(PriceList.IsCurrent()).Dump();
PS, Your example doesn't compile, so I'm guessing that you mean
public static Expression<Func<PriceList, bool>> IsCurrent()
{
...
and
List<PriceList> plList = new List<PriceList>()
...