top "N" rows in each group using hibernate criteria - spring

Top / Bottom / Random "N" rows in each group using Hibernate Criteria / Projections
How to retrieve top 5 Questions for Each Sub Topic
DetachedCriteria criteria = DetachedCriteria.forClass(Question.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("questionId"));
projList.add(Projections.groupProperty("subTopicId"));
criteria.setProjection(projList);
List<Object> resultList = (List<Object>) getHibernateTemplate().findByCriteria(criteria);
Iterator<Object> itr = resultList.iterator();
List<Integer> questionIdList = new ArrayList<Integer>();
while(itr.hasNext()){
Object ob[] = (Object[])itr.next();
System.out.println(ob[0]+" -- "+ob[1]);
}
I am Using the Code Below for Getting Result Temporally, Is there any solution from Hibernate using Criteria API / Any other alternate way to get the result
Set<Integer> getQuestionsBySubTopicWithLimit(Set<Integer> questionIdsSet, Integer subjectId, Integer limit, Integer status) {
DetachedCriteria criteria = DetachedCriteria.forClass(Question.class);
if(subjectId!=null && subjectId!=0){
criteria.add(Restrictions.eq("subjectId", subjectId));
}
if(status!=null){
criteria.add(Restrictions.eq("status", status));
}
if(questionIdsSet!=null && !questionIdsSet.isEmpty()){
criteria.add(Restrictions.not(Restrictions.in("questionId", questionIdsSet)));
}
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("questionId"));
projList.add(Projections.property("subTopicId"));
criteria.add(Restrictions.sqlRestriction("1=1 order by sub_topic_id, rand()"));
criteria.setProjection(projList);
List<Object> resultList = (List<Object>) getHibernateTemplate().findByCriteria(criteria);
Iterator<Object> itr = resultList.iterator();
Set<Integer> tmpQuestionIdsSet = new HashSet<Integer>();
Integer subTopicId = 0, tmpSubTopicId = 0;
Integer count = 0;
while(itr.hasNext()){
Object ob[] = (Object[])itr.next();
if(count==0){
subTopicId = (Integer) ob[1];
}
tmpSubTopicId = (Integer) ob[1];
if(tmpSubTopicId!=subTopicId){
subTopicId = tmpSubTopicId;
count = 0;
}
count++;
if(count<=limit){
tmpQuestionIdsSet.add((Integer) ob[0]);
}
}
return tmpQuestionIdsSet;
}

Related

Dynamics crm + plugin logic to update zero values

I need to perform the sum of each field across multiple records of the same entity and update the values on the same entity. Along with this I also need to store its formula.
AttributeList = { "price ", "quantity", "contact.revenue", "opportunity.sales"}
Below is the logic
foreach (var attribute in attributeList)
{
Decimal fieldSum = 0;
string computedNote = string.Empty;
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
if (entity.Attributes[attribute] != null)
{
string type = entity.Attributes[attribute].GetType().Name;
Decimal attrValue = 0;
if (type == "AliasedValue")
{
AliasedValue aliasedFieldValue = (entity.GetAttributeValue<AliasedValue>(attribute));
attrValue = aliasedFieldValue.Value.GetType().Name == "Decimal" ? (Decimal)aliasedFieldValue.Value : (Int32)aliasedFieldValue.Value;
}
else
{
attrValue = entity.Attributes[attribute].GetType().Name == "Decimal" ? entity.GetAttributeValue<Decimal>(attribute) : entity.GetAttributeValue<Int32>(attribute);
}
fieldSum += attrValue;
computedNote += $"+{Convert.ToInt32(attrValue).ToString()}";
}
}
else
{
computedNote += $"+0";
}
}
Entity formula = new Entity("formula");
if (fieldSum != 0)
{
if (attribute.Contains("opportunity"))
{
opportunity[attributeName] = fieldSum;
entityName = Opportunity.EntityLogicalName;
attributeName = attribute;
recordId = Id;
}
else if (attribute.Contains("contact"))
{
contact[attributeName] = fieldSum;
entityName = Contact.EntityLogicalName;
attributeName = attribute;
recordId = Id;
}
else
{
mainentity[attribute] = fieldSum;
entityName = mainEntity.EntityLogicalName;
attributeName = attribute;
recordId = Id;
}
formula.Attributes["ice_entity"] = entityName;
formula.Attributes["ice_attribute"] = attributeName;
formula.Attributes[entityName + "id"] = new EntityReference(entityName, recordId);
formula.Attributes["ice_computednote"] = computedNote.Remove(0, 1);
requestsCollection.Entities.Add(formula);
}
}
requestsCollection.Entities.Add(opportunity);
requestsCollection.Entities.Add(contact);
requestsCollection.Entities.Add(mainentity);
Values in both records could be as follows
Record 1
Price = 500
Quantity = 25
Revenue = 100
Sales = 10000
Volume = 0
Record 2
Price = 200
Quantity = 10
Revenue = 100
Sales = -10000
Volume = 0
Record 3 (Values after calculation that are to be updated in the third entity and Formula to be stored mentioned in brackets)
Price = 700 Formula = (500+200)
Quantity = 35 Formula = (25+10)
Revenue = 200 Formula =(100+100)
Sales = 0 Formula =(10000 + (-10000))
Volume = 0 No Formula to be created
I am checking if the fieldsum is not equal to zero (to update both positive and negative values) and then updating the values in the respective entity. However for values that became zero after the calculation. I also need to update them and create formula for the same. Avoiding the values that were zero by default.
As shown in above example, I want to update sales field value and create formula record for the same as '10000+-10000' but do not want volume field value to be updated or the formula to be created for it. How can i embed this logic in my code?
Add a flag (updateFormula) to indicate whether checksum and formula required to update in related entities. Then, instead of checking fieldSum != 0, check updateFormula is true to update the related records.
attributeList = { "price", "quantity", "contact.revenue", "opportunity.sales"}
foreach (var attribute in attributeList)
{
Decimal fieldSum = 0;
string computedNote = string.Empty;
bool updateFormula = false;
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
if (entity.Attributes[attribute] != null)
{
string type = entity.Attributes[attribute].GetType().Name;
Decimal attrValue = 0;
if (type == "AliasedValue")
{
AliasedValue aliasedFieldValue = (entity.GetAttributeValue<AliasedValue>(attribute));
attrValue = aliasedFieldValue.Value.GetType().Name == "Decimal" ? (Decimal)aliasedFieldValue.Value : (Int32)aliasedFieldValue.Value;
}
else
{
attrValue = entity.Attributes[attribute].GetType().Name == "Decimal" ? entity.GetAttributeValue<Decimal>(attribute) : entity.GetAttributeValue<Int32>(attribute);
}
fieldSum += attrValue;
computedNote += Convert.ToInt32(attrValue).ToString();
updateFormula = true;
}
}
else
{
computedNote += 0;
}
}
Entity formula = new Entity("formula");
if (updateFormula)
{
// Logic to update formula and checksum
}
}

How to arrange array of objects with same property value?

I have an person model with two property like this:
int id;
String name;
and some object with this data:
person0 = {1,"James"};
person1 = {2,"James"};
person2 = {3,"James"};
person3 = {4,"Barbara"};
person4 = {5,"Barbara"};
person5 = {6,"Ramses"};
and array contain objects:
firstArray = [person0, person1, person2, person3, person4, person5];
Therefore how can have this array:
secondArray = [
[person0, person1, person2],
[person3, person4],
[person5]
]
Thank you.
If language does not matter.
map = new Map();
for (persona of personas) {
name = persona.name;
arrayForName = map.get(name);
if (arrayForName == null) {
arrayForName = [];
map.put(name, arrayForName);
}
arrayForName.put(persona)
}
The idea is to have a map (which is a collection key->value).
The value of the map should in turn be an array.
To add elements efficiently, you iterate only once through the data, and add arrays each time a new key is discovered (i.e. the name).
In Java it would be something like:
Map<String, List<Persona>> map = new HashMap<>();
for (Persona persona : personas) {
String name = persona.getName();
List<Persona> listForName = map.get(name);
if (listForName == null) {
listForName = new ArrayList<Persona>();
map.put(name, listForName);
}
listForName.add(persona)
}
Try this code in Java Android:
ArrayList<ArrayList<Person>> secondArr = new ArrayList<>();
ArrayList<Course> tempArr = new ArrayList<>();
for (int i = 0; i < firstArr.size(); i++) {
if ((i + 1) >= firstArr.size()) {
tempArr.add(firstArr.get(i));
secondArr.add(tempArr);
} else {
if (firstArr.get(i).name .equals( firstArr.get(i + 1).name) ) {
tempArr.add(firstArr.get(i));
} else {
tempArr.add(firstArr.get(i));
secondArr.add(tempArr);
tempArr = new ArrayList<>();
}
}
}
Finally secondArr prepared.
And if list not sorted we can use code like this:
for (int i = 0; i <firstArr.size() ; i++) {
boolean isAdd = false;
for (int j = 0; j < secondArr.size() ; j++) {
if (secondArr.get(j).get(0).getName().equals(firstArr.get(i).getName())){
secondArr.get(j).add(firstArr.get(i));
isAdd =true;
break;
}
}
if (!isAdd){
ArrayList<Person> arrayList = new ArrayList<>();
arrayList.add(firstArr.get(i));
secondArr.add(arrayList);
}
}

java.lang.NumberFormatException when reading text from keyboard

This program reads numbers from keyboard and sums it until user writes "total", but then I get a java.lang.NumberFormatException.
Boolean isTotal = false;
int sum = 0;
while(!isTotal)
{
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String s = br.readLine();
if(s=="total")
{
isTotal = true;
}
if(!isTotal)
sum = sum + Integer.parseInt(s);
}
System.out.println(sum);
Boolean isTotal = false;
int sum = 0;
while(!isTotal)
{
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String s = br.readLine();
if(s.equals("total"))
{
isTotal = true;
}
if(!isTotal)
sum = sum + Integer.parseInt(s);
}
System.out.println(sum);

Entity Framework and LINQ: Is there anyway to auto reflect the renamed entity in LINQ query

I was trying to change the table names in the entity model or database but the old names are already use in many places in the application. Is there any way to auto reflect renamed entities or tables in the LINQ query or code.
Let say I have tables tblDepartment, tblEmployee and tblEmployeeDepartment. These tables are used in the code(LINQ) on many places. I like to change these tables names to Department, Employee and EmployeeDepartment. So, is there anyway to auto reflect name in LINQ or code when I change table names either using Database First or Model First approach.
P.S. The application is based on .Net 3.5
Working With linq and Entity Framework plus excel reports|Enjoy
public static string strMessage = "";
public SchoolEntities dbContext;
public string login(string strUsername, string strPassword)
{
dbContext = new SchoolEntities();
var linqQuery = from User in dbContext.People
where User.FirstName == strUsername && User.LastName == strPassword
select User;
if (linqQuery.Count() == 1)
{
strMessage = "Good";
}
else
{
strMessage = "Bad";
}
return strMessage;
}
public Object LoadPersonDetails()
{
dbContext = new SchoolEntities();
//DataTable dtPerson = new DataTable();
var linqQuery = from users in dbContext.People
select users;
//List<Person> Users = linqQuery.ToList();
//dtPerson = linqQuery.ToList();
return linqQuery;
}
public void InsertPerson(string strLName, string strFName, string strHireDate, string EnrollmentDate)
{
dbContext = new SchoolEntities();
Person NewPerson = dbContext.People.Create();
NewPerson.LastName = strLName;
NewPerson.FirstName = strFName;
NewPerson.HireDate = Convert.ToDateTime(strHireDate);
NewPerson.EnrollmentDate = Convert.ToDateTime(EnrollmentDate);
dbContext.People.Add(NewPerson);
dbContext.SaveChanges();
}
public void DeleteUser(int intPersonID)
{
//dbContext = new SchoolEntities();
using (dbContext = new SchoolEntities())
{
Person Person = dbContext.People.Where(c => c.PersonID == intPersonID).FirstOrDefault();
if (Person != null)
{
dbContext.People.Remove(Person);
dbContext.SaveChanges();
}
}
}
public void ModifyPerson(int intPersonID, string strLName, string strFName, string strHireDate, string EnrollmentDate)
{
var UpdatePerson = dbContext.People.FirstOrDefault(s => s.PersonID == intPersonID);
UpdatePerson.LastName = strLName;
UpdatePerson.FirstName = strFName;
UpdatePerson.HireDate = Convert.ToDateTime(strHireDate);
UpdatePerson.EnrollmentDate = Convert.ToDateTime(EnrollmentDate);
dbContext.SaveChanges();
}
private Excel.Application XApp = null; //Creates the Excel Document
private Excel.Workbook XWorkbook = null; //create the workbook in the recently created document
private Excel.Worksheet XWorksheet = null; //allows us to work with current worksheet
private Excel.Range XWorkSheet_range = null; // allows us to modify cells on the sheet
public void Reports()
{
dbContext = new SchoolEntities();
var linqQuery = (from users in dbContext.StudentGrades
group users by new { users.EnrollmentID, users.CourseID, users.StudentID, users.Grade }
into UserGroup
orderby UserGroup.Key.CourseID ascending
select new { UserGroup.Key.EnrollmentID, UserGroup.Key.CourseID, UserGroup.Key.StudentID, UserGroup.Key.Grade }).ToList();
var RatingAverage = dbContext.StudentGrades.Average(r => r.Grade);
var GradeSum = dbContext.StudentGrades.Sum(r => r.Grade);
/*var linqQuery = (from users in dbContext.StudentGrades
orderby users.CourseID descending
select users).ToList();*/
//Array Motho = linqQuery.ToArray();
XApp = new Excel.Application();
XApp.Visible = true;
XWorkbook = XApp.Workbooks.Add(1);
XWorksheet = (Excel.Worksheet)XWorkbook.Sheets[1];
//Create column headers
XWorksheet.Cells[2, 1] = "EnrollmentID";
XWorksheet.Cells[2, 2] = "CourseID";
XWorksheet.Cells[2, 3] = "StudentID";
XWorksheet.Cells[2, 4] = "Grade";
//XWorksheet.Cells[2, 5] = "Enrollment Date";
int row = 3;
foreach (var Mothos in linqQuery)
{
XWorksheet.Cells[row, 1] = Mothos.EnrollmentID.ToString();
XWorksheet.Cells[row, 2] = Mothos.CourseID.ToString();
XWorksheet.Cells[row, 3] = Mothos.StudentID.ToString();
XWorksheet.Cells[row, 4] = Mothos.Grade.ToString();
row++;
}
int rows = linqQuery.Count();
XWorksheet.Cells[rows + 4, 3] = "Grades Average";
XWorksheet.Cells[rows + 4, 4] = RatingAverage.Value.ToString();
XWorksheet.Cells[rows + 5, 3] = "Grades Sum";
XWorksheet.Cells[rows + 5, 4] = GradeSum.Value.ToString();
//XWorkSheet_range.ColumnWidth = 30;
//XWorksheet.Cells.AutoFit();
}
Working with xml | add, modify and delete xml data
string conn = "E:/School/Development Sftware/2014/ReadWriteUpdateDeleteXML/DataService/Profiles.xml";
public string InsertProfile(string fname, string lname, string phone, string gender)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
XmlElement subRoot = xmlDoc.CreateElement("Profile");
//add first name
XmlElement appendedElementFname = xmlDoc.CreateElement("FirstName");
XmlText xmlTextFname = xmlDoc.CreateTextNode(fname.Trim());
appendedElementFname.AppendChild(xmlTextFname);
subRoot.AppendChild(appendedElementFname);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add last name
XmlElement appendedElementLname = xmlDoc.CreateElement("LastName");
XmlText xmlTextLname = xmlDoc.CreateTextNode(lname.Trim());
appendedElementLname.AppendChild(xmlTextLname);
subRoot.AppendChild(appendedElementLname);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add phone
XmlElement appendedElementPhone = xmlDoc.CreateElement("Phone");
XmlText xmlTextPhone = xmlDoc.CreateTextNode(phone.Trim());
appendedElementPhone.AppendChild(xmlTextPhone);
subRoot.AppendChild(appendedElementPhone);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add gender
XmlElement appendedElementGender = xmlDoc.CreateElement("Gender");
XmlText xmlTextGender = xmlDoc.CreateTextNode(gender.Trim());
appendedElementGender.AppendChild(xmlTextGender);
subRoot.AppendChild(appendedElementGender);
xmlDoc.DocumentElement.AppendChild(subRoot);
xmlDoc.Save(conn);
return "Profile Saved";
}
public DataSet LoadXML()
{
DataSet dsLog = new DataSet();
dsLog.ReadXml(conn);
return dsLog;
}
public string DeleteProfile(string fname)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
//XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/Profiles/Profile[#FirstName=" + fname + "]");
//if (nodeToDelete != null)
//{
// nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
//}
//xmlDoc.Save("C:/Users/Shazzy/Documents/Visual Studio 2010/Projects/ReadWriteUpdateDeleteXML/DataService/Profiles.xml");
//return "Deleted";
foreach (XmlNode node in xmlDoc.SelectNodes("Profiles/Profile"))
{
if (node.SelectSingleNode("FirstName").InnerText == fname)
{
node.ParentNode.RemoveChild(node);
}
}
xmlDoc.Save(conn);
return "Deleted";
}
public string ModifyProfile(string fname, string lname, string phone, string gender)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
foreach (XmlNode node in xmlDoc.SelectNodes("Profiles/Profile"))
{
if (node.SelectSingleNode("FirstName").InnerText == fname)
{
node.SelectSingleNode("FirstName").InnerText = fname;
node.SelectSingleNode("LastName").InnerText = lname;
node.SelectSingleNode("Phone").InnerText = phone;
node.SelectSingleNode("Gender").InnerText = gender;
}
}
xmlDoc.Save(conn);
return "Updated";
}
Working with edm and Excel-grouped report
public void Function_Create_Sales()
{
DBContext = new PubsEntities();
var linqStores = from Sales in DBContext.sales
orderby Sales.stor_id
select Sales;
var lstStore = linqStores.ToList();
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
Excel.Workbook xlBook = xlApp.Workbooks.Add(1);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
int GroupTotal = 0;
int GrandTotal = 0;
int ExcelRow = 5;
string intTemp = lstStore[0].stor_id;
xlSheet.Cells[4, 1] = lstStore[0].stor_id;
//Create column headers
xlSheet.Cells[1, 1] = "Sales Grouped By Store";
xlSheet.Cells[3, 1] = "Group header";
xlSheet.Cells[3, 2] = "Store ID";
xlSheet.Cells[3, 3] = "Order Number";
xlSheet.Cells[3, 4] = "Order Date";
xlSheet.Cells[3, 5] = "Quantity";
xlSheet.Cells[3, 6] = "payments";
xlSheet.Cells[3, 7] = "title ID";
for (int count = 0; count < lstStore.Count; count++)
{
if (intTemp == lstStore[count].stor_id)
{
xlSheet.Cells[ExcelRow, 2] = lstStore[count].stor_id.ToString();
xlSheet.Cells[ExcelRow, 3] = lstStore[count].ord_date.ToString();
xlSheet.Cells[ExcelRow, 4] = lstStore[count].qty.ToString();
xlSheet.Cells[ExcelRow, 5] = lstStore[count].payterms.ToString();
xlSheet.Cells[ExcelRow, 5] = lstStore[count].title_id.ToString();
ExcelRow++;
GroupTotal++;
GrandTotal++;
}
else
{
xlSheet.Cells[ExcelRow, 5] = "Total for: " + intTemp + " = " + GroupTotal.ToString();
ExcelRow++;
intTemp = lstStore[count].stor_id;
xlSheet.Cells[ExcelRow, 1] = lstStore[count].stor_id;
count--;
GroupTotal = 0;
ExcelRow++;
}
}
xlSheet.Cells[ExcelRow, 5] = "Total for: " + intTemp + " = " + GroupTotal.ToString();
ExcelRow++;
xlSheet.Cells[ExcelRow, 5] = "Grand Total = " + GrandTotal.ToString();
xlSheet.Rows.Columns.AutoFit();
}

JTable + sorting column, but row is not sorted

I have created a JTable, the table contains 4 rows, and for a specific row, I have overridden the sorting and its working fine only on that column.
Status Scheduled Date Scheduled time Status
false 30/01/2012 02:00:00 Scheduled
false 29/01/2012 14:58:00 Scheduled
false 29/01/2012 15:50:00 Scheduled
For Scheduled Date, which I try to sort, it would sort, but the respecitve rows are not being updated.
Here is my code for sorting
public static void sortColumn(DefaultTableModel model, int colIndex,
boolean sortingOrder) {
Vector<?> data = model.getDataVector();
Object[] colData = new Object[model.getRowCount()];
SortedSet<Object> dataCollected = null;
List<Date> dateCollected;
boolean dateFlag = false;
dateCollected = new ArrayList<Date>();
// Copy the column data in an array
for (int i = 0; i < colData.length; i++) {
Object tempData = ((Vector<?>) data.get(i)).get(colIndex);
if ((colIndex == 1 || colIndex == 4)
&& tempData.toString().contains("/")) {
String[] _scheduledDate1 = ((String) tempData).split("/");
Calendar _cal1 = Calendar.getInstance();
_cal1.set(Integer.parseInt(_scheduledDate1[2]),
Integer.parseInt(_scheduledDate1[1]) - 1,
Integer.parseInt(_scheduledDate1[0]));
dateCollected.add(_cal1.getTime());
dateFlag = true;
} else {
colData[i] = ((Vector<?>) data.get(i)).get(colIndex);
}
}
// DateCompare compare = new DateCompare();
if (!dateFlag) {
dataCollected = new TreeSet<Object>();
dataCollected.add(colData);
dateFlag = false;
}
// Copy the sorted values back into the table model
if ((colIndex == 1 || colIndex == 4) && dateFlag) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sortOrder = !sortOrder;
if (sortOrder) {
Collections.sort(dateCollected);
} else {
Collections.sort(dateCollected, Collections.reverseOrder());
}
colData = dateCollected.toArray();
for (int i = 0; i < colData.length; i++) {
((Vector<Object>) data.get(i)).set(colIndex,
sdf.format(((Date) colData[i]).getTime()));
}
} else {
for (int i = 0; i < colData.length; i++) {
((Vector<Object>) data.get(i)).set(colIndex, colData[i]);
}
}
model.fireTableStructureChanged();
}
How to I get the entire row update accordingly?
I found the problem, my object against I was comparing was wrong, I've change the code for the same it all works fine.
I implemented QuickSort algorithm to sort the vector on the specific column I need.

Resources