I know that BeanPropertyRowMapper<>() can wrap fields comparing database fields to Class fields by name.
But why when I'm using keyword "AS" i get an error.
jdbcTemplate code
public Book showBook(int id) {
return jdbcTemplate.query("SELECT books.id , books.name, books.author, books.year, books.people_id as peopleId, people.id as personId, people.name as personName FROM books LEFT JOIN people ON books.people_id = people.id WHERE books.id = ?",
new Object[]{id}, new BeanPropertyRowMapper<>(Book.class))
.stream().findAny().orElse(null);
}
Class fields
private int id;
#NotEmpty (message = "Name should not be empty")
#Size (min = 2, max = 255, message = "Name should be correct")
private String name;
#NotEmpty (message = "Field author should not be empty")
#Size (min = 2, max = 255, message = "Field author should be correct")
private String author;
#Min(value = 0)
private int year;
private int peopleId;
private int personId;
private String personName;
Related
I am converting an MVC C# application to VB.
I'm running across problem converting Linq.
I've got to do a number of these, so prefer a nice explanation.
When I convert to VB I seem to get null int error which I'm not getting in the C# version.
System.NotSupportedException: 'Unable to cast the type 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.'
I've tried online converter but they are not giving valid answers.
C#
public List<notesselect> getNotes(int? catid, int? userid, int page = 1, int size = 10)
{
// pagination stuff
int startindex = 1;
startindex = ((page - 1) * size);
//get all noted which is created by user or shared to user
var notes = (from c in db.Notes
join Category in db.Categorys on c.CategoryId equals Category.CategoryId
join d in db.Users on c.CreatedBy equals d.UserId
join p in db.NotesAuth on new { NotesId = c.NotesId, isactive = true } equals new { NotesId = p.NotesId, isactive = p.IsActive } into ps
from p in ps.DefaultIfEmpty()
where c.IsActive == true
&& (c.CreatedBy == userid || p.UserId == userid)
&& (catid != null ? c.CategoryId == catid : true)
select new notesselect
{
CategoryId = c.CategoryId,
CategoryName = Category.Category,
title = c.Title,
createby = d.FirstName + " " + d.LastName,
noteid = c.NotesId,
createdate = c.ChangeDate,
lastModifiedOn = c.ChangeDate.ToString()
}).OrderByDescending(x => x.createdate);
if (page > 0)
{
return notes.Skip(startindex).Take(size).ToList();
}
else
{
return notes.ToList();
}
}
/// <summary>
/// Get Total Count of Notes
/// </summary>
/// <param name="catid">Category Id</param>
/// <param name="userid">User Id</param>
/// <returns></returns>
public int getNoteCount(int? catid, int? userid)
{
var total = (from c in db.Notes
join Category in db.Categorys on c.CategoryId equals Category.CategoryId
join d in db.Users on c.CreatedBy equals d.UserId
join p in db.NotesAuth on new { NotesId = c.NotesId, isactive = true } equals new { NotesId = p.NotesId, isactive = p.IsActive } into ps
from p in ps.DefaultIfEmpty()
where c.IsActive == true
&& (c.CreatedBy == userid || p.UserId == userid)
&& (catid != null ? c.CategoryId == catid : true)
select c).Count();
return total;
}
Vb Converted code
Public Function getNotes(ByVal catid? As Integer, ByVal userid? As Integer, Optional ByVal page As Integer = 1, Optional ByVal size As Integer = 10) As List(Of notesselect)
' pagination stuff
Dim startindex As Integer = 1
startindex = 1 '((page - 1) * size)
'get all noted which is created by user or shared to user
Dim notes = (From c In db.Notes
Join Category In db.Categorys On CType(c.CategoryId, Integer?) Equals CType(Category.CategoryId, Integer?)
Join d In db.Users On c.CreatedBy Equals CType(d.UserId, Integer?)
Group Join p In db.NotesAuth On New With {
.NotesId = c.NotesId,
.isactive = True
} Equals New With {
.NotesId = p.NotesId,
.isactive = p.IsActive
} Into ps = Group
From p In ps.DefaultIfEmpty()
Where c.IsActive = True AndAlso (userid.Equals(c.CreatedBy) OrElse userid.Equals(p.UserId)) AndAlso (If(catid IsNot Nothing, catid.Equals(c.CategoryId), True))
Select New notesselect With {
.CategoryId = c.CategoryId,
.CategoryName = Category.Category,
.title = c.Title,
.createby = d.FirstName & " " & d.LastName,
.noteid = c.NotesId,
.createdate = c.ChangeDate,
.lastModifiedOn = CStr(c.ChangeDate.ToString)
}).OrderByDescending(Function(x) x.createdate)
If page > 0 Then
Return notes.Skip(startindex).Take(size).ToList()
Else
Return notes.ToList()
End If
'Dim InvoiceNo = If(dbContext.table.where(Function(x) DirectCast(x.ICOD, System.Nullable(Of Integer))), "NCOD")
End Function
''' <summary>
''' Get Total Count of Notes
''' </summary>
''' <param name="catid">Category Id</param>
''' <param name="userid">User Id</param>
''' <returns></returns>
Public Function getNoteCount(ByVal catid? As Integer, ByVal userid? As Integer) As Integer
Dim total = (
From c In db.Notes
Join Category In db.Categorys On CType(c.CategoryId, Integer?) Equals Category.CategoryId
Join d In db.Users On CType(c.CreatedBy, Integer?) Equals CType(d.UserId, Integer?)
Group Join p In db.NotesAuth On New With {
Key .NotesId = c.NotesId,
Key .isactive = True
} Equals New With {
Key .NotesId = p.NotesId,
Key .isactive = p.IsActive
} Into ps = Group
From p In ps.DefaultIfEmpty()
Where c.IsActive = True AndAlso (userid.Equals(c.CreatedBy) OrElse userid.Equals(p.UserId)) AndAlso (If(catid IsNot Nothing, catid.Equals(c.CategoryId), True))
Select c).Count()
Return total
End Function
I have a table in postgres
CREATE TABLE employer_visit(
employer_id INTEGER REFERENCES employer,
visit_counter INTEGER NOT NULL, -- counter on current date
visit_before_date_total_counter INTEGER NOT NULL, -- total, since service has started
date DATE,
PRIMARY KEY(employer_id, date)
);
I need to find top employers by visits from last 30 days - (ordered list of employer_visit by diff between visit_before_date_total_counter in last record and last record 30 days ago)
I have tried this hql query
Query<EmployerVisit> query = getSession().createQuery(
"SELECT ev FROM EmployerVisit ev " +
"WHERE ev.employerVisitId.date = (SELECT MAX (groupedEv.employerVisitId.date) FROM EmployerVisit groupedEv " +
"WHERE groupedEv.employerVisitId.employerId = ev.employerVisitId.employerId) " +
"AND " +
"ev.employerVisitId.date = (SELECT MAX (groupedEv2.employerVisitId.date) < :date FROM EmployerVisit groupedEv2 " +
"WHERE groupedEv2.employerVisitId.employerId = ev.employerVisitId.employerId) " +
"ORDER BY (groupedEv.visitCounter + groupedEv.visitBeforeDateTotalCounter) - (groupedEv2.visitCounter + groupedEv2.visitBeforeDateTotalCounter) DESC"
).setMaxResults(size).setParameter("date", calendar.getTime());
But it falls with
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'groupedEv.visitCounter'
Becouse the table groupedEv doesn't exist after ORDER BY
It is possible to use depricated SqlQuery for this case in hibernate but I prefere hql, please help, thanks.
UPDATE! - Entity and EmbeddedId Class without setters and getters
#Entity
#Table(name = "employer_visit")
public class EmployerVisit {
#EmbeddedId
private EmployerVisitId employerVisitId;
#Column(name = "visit_counter")
private Integer visitCounter;
#Column(name = "visit_before_date_total_counter")
private Integer visitBeforeDateTotalCounter;
public EmployerVisit() {
employerVisitId = new EmployerVisitId();
visitCounter = 0;
visitBeforeDateTotalCounter = 0;
}
}
#Embeddable
public class EmployerVisitId implements Serializable {
#Column(name = "employer_id")
private Integer employerId;
#Column(name = "date")
private Date date;
public EmployerVisitId() {
}
}
This is the Answer
Query<Object> query = getSession().createQuery(
"SELECT ev, SUM(ev.visitCounter) AS counter FROM EmployerVisit AS ev " +
"WHERE ev.employerVisitId.date > :date " +
"GROUP BY ev.employerVisitId.employerId, ev.employerVisitId.date " +
"ORDER BY counter DESC").setMaxResults(size).setParameter("date", calendar.getTime());
List<EmployerVisitDto> top = new ArrayList<>();
for (Object result : query.list()) {
Object[] dividedResult = (Object[]) result;
EmployerVisit employerVisit = (EmployerVisit) dividedResult[0];
EmployerVisitDto employerVisitDto = getEmployer(employerVisit.getEmployerId()).toEmployerVisitDto();
employerVisitDto.setPeopleVisited(((Long) dividedResult[1]).intValue());
top.add(employerVisitDto);
}
return top;
I am trying to query faculties that have 3 subjects mysql statement is as the following
select * from faculty_subject where subject_id in(1 and 3 and 2);
where 1, 2, 3 are subject ids. I only want courses that have all these subjects so that reason I am using and. But I do not why my spring query is not working. I tried different ways but it's returning faculties with the first subject id in this case 1. Here is my spring query
#Query(value = "select * from faculty_subject where subject_id in(?#{[0]} and ?#{[1]} and ?#{[1]})", nativeQuery = true)
List<FacultySubject> getFacultyBySubjects(long subjectTop, long subjectMid, long subjectBottom);
another one that did not work
#Query(value = "select * from faculty_subject where subject_id in(?1 and ?2 and ?3)", nativeQuery = true)
List<FacultySubject> getFacultyBySubjects(long subjectTop, long subjectMid, long subjectBottom);
another query
#Query(value = "select * from faculty_subject where subject_id in(:#{#subjectTop} and :#{#subjectMid} and :#{#subjectBottom})", nativeQuery = true)
List<FacultySubject> getFacultyBySubjects(#Param("subjectTop") long subjectTop,
#Param("subjectMid") long subjectMid,
#Param("subjectBottom") long subjectBottom);
Entity
#Entity
public class FacultySubject {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private long facultyId;
private int subjectId;
public FacultySubject(long facultyId, int subjectId) {
this.facultyId = facultyId;
this.subjectId = subjectId;
}
public FacultySubject() {
}
... getters and setters
#Query(value = "select * from faculty_subject where subject_id in(?1 , ?2 , ?3) group by faculty_id having count(*)==3", nativeQuery = true)
List<FacultySubject> getFacultyBySubjects(long subjectTop, long subjectMid, long subjectBottom);
I have a database table that have a structure like this:
ID Integer Auto Incresement
Name VarChar
Status VarChar
Sample records:
ID Name Status
1 record 1 Outstanding
2 record 2 Outstanding
3 record 3 Aging
4 record 4 Outstanding
5 record 5 Aging
6 record 6 Outstanding
In the table, there are two main status: "Outstanding" and "Aging". I want to count how many records with status of "Outstanding" and how many records with status of "Aging" available in the table.
This is a sample LINQ Query:
Using DC = DataClassesDataContext.Create()
Dim dataTable = From Count(Outstanding), Count(Aging) In DC.MyTable _
Where item.Status = "Outstanding" OrElse item.Status = "Aging" _
Group By item.Status _
Select item
End Using
The expected result should be:
Outstanding Aging
4 2
Can you help me to design a LINQ to achive the result?
Try this:
Dim MyTable = { _
New With {.ID = 1, .Name = "record 1", .Status = "Outstanding"},
New With {.ID = 2, .Name = "record 2", .Status = "Outstanding"},
New With {.ID = 3, .Name = "record 3", .Status = "Aging"},
New With {.ID = 4, .Name = "record 4", .Status = "Outstanding"},
New With {.ID = 5, .Name = "record 5", .Status = "Aging"},
New With {.ID = 6, .Name = "record 6", .Status = "Outstanding"}
}
Dim dataTable = _
From item In MyTable
Group By Key = item.Status Into Xs = Group
Select New With {.Status = Key, .Count = Xs.Count()}
I get this result:
Try this :-
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var test = new List<Sample>();
test.Add(new Sample{ID=1,Name="record 1",Status="Outstanding"});
test.Add(new Sample{ID=2,Name="record 2",Status="Outstanding"});
test.Add(new Sample{ID=3,Name="record 3",Status="Aging"});
test.Add(new Sample{ID=4,Name="record 4",Status="Outstanding"});
test.Add(new Sample{ID=5,Name="record 5",Status="Outstanding"});
test.Add(new Sample{ID=6,Name="record 6",Status="Aging"});
var result = from row in test
group row by "Count" into g
where g.FirstOrDefault() != null
select new
{
//Status = g.Key,
Outstanding = g.Where(C => C.Status == "Outstanding").Count(),
Aging = g.Where(C => C.Status == "Aging").Count()
};
Console.WriteLine("Outstanding"+" "+"Aging");
foreach(var item in result)
{
Console.WriteLine(" "+item.Outstanding+" "+item.Aging);
}
}
}
public class Sample
{
public int ID {get;set;}
public string Name {get;set;}
public string Status {get; set;}
}
result :-
you can run above sample code using following link - https://dotnetfiddle.net/xC2NXm
suggest improvement :)
I attempt to select some instance using where clause
public static List<RSSItem> getRSSItem(int x1, int x2) {
EntityManagerFactory emf = DBHandler.getEmf();
EntityManager em = DBHandler.getEm(emf);
String query =
"SELECT items FROM RSSItem items "
+ "WHERE items.id <= :x1 AND "
+ "items.id >= :x2";
List<RSSItem> results =
(List<RSSItem>) em.createQuery(query).
setParameter("x1", x1).
setParameter("x2", x2).
getResultList();
return results;
}
the RSSItem attributes :
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
String title;
String link;
String description;
String pubdate;
String content;
HashMap<String, Integer> keyword = new HashMap();
HashMap<String, Integer> keywordBefore = new HashMap();
// TreeMap <String, Integer> keyword = new TreeMap();
String feed;
the problem is it always return a list with 0 size. what's wrong with my select query?
With the values x1 = 1 and x2 = 500, the query turns into...
SELECT items FROM RSSItem items
WHERE items.id <= 1
AND items.id >= 500
Since no id's are less or equal to 1 and greater or equal to 500 at the same time, the query will give no hits. What you want is probably;
String query =
"SELECT items FROM RSSItem items "
+ "WHERE items.id >= :x1 AND "
+ "items.id <= :x2";
...which with your example data will find all id's between 1 and 500, inclusive.