In query in hibernate? - oracle

I am using hibernate and i am able to get the list of employeees having salary as 2000 using this.
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();
Now i want to get the employees having salary as 2000 and 3000 .
How i can use in query in hibernate using criteria?

You can use Restrictions.in i.e.
Criteria cr = session.createCriteria(Employee.class);
List<Integer> salaryList = new ArrayList<Integer>();
salaryList.add(2000);
salaryList.add(3000);
criteria.add(Restrictions.in("salary", salaryList));
List results = cr.list();

Friend you can use this
List list =session.createCriteria(Employee.class).
add(Restrictions.between("salary",2000,3000);
This between method very usefull

Related

SQL Group by and having in coherence

I would like to execute the following query in Coherence
Select AVG(Salary)
, Count(*)
from Employees
group by Company
Having AVG(Salary)> 1000
I was trying to use GroupAggregators but I have problem with refering to an avarage salary as it is not defined in the Employee Class but in Aggregator:
GroupAggregator high_salary = GroupAggregator.createInstance("getDepartment"
, new DoubleAverage("getSalary")
, new GreaterFilter("DoubleAverage", 1000));
How can I do this?
You should use IdentityExtractor.INSTANCE instead of "DoubleAverage" as a value extractor in GreaterFilter, because value passed to this filter is the avarage salary itself, not some object with "DoubleAverage" property.
But if you would like to get avarage salary as well as count (that would be consistent with your SQL query), you will have to use CompositeAggregator. In that case the value passed to the filter will not be a number anymore, but a List and you will have to use ValueExtractor that will extract avarage salary from this list. In Coherence 12.2.1 it would look like this:
DoubleAverage<Employee> avgSalary = new DoubleAverage<>(Employee::getSalary);
Count<String, Employee> count = new Count<>();
CompositeAggregator<String, Country> compositeAggregator = CompositeAggregator
.createInstance(new InvocableMap.EntryAggregator[] { avgSalary, count });
ValueExtractor<Object, ? extends Double> salaryExtractor =
list -> ((List<Number>) list).get(0).doubleValue();
Filter having = Filters.greater(salaryExtractor, 1000.0);
GroupAggregator<String, Country, Employee, String, List> groupAggregator =
GroupAggregator.createInstance(Employee::getDepartment, compositeAggregator, having);
It can be done also in older versions, but it would require some more work to implement salaryExtractor without using lambda expression.

Best way to get individual days from a column, using LINQ

I have the following data in one MSSQL Table column
2011-06-20 11:53:32.000
2011-06-20 11:54:24.000
2011-06-20 11:55:45.000
2011-08-05 10:24:12.000
2011-08-05 10:25:28.000
2011-08-05 10:26:20.000
2011-08-05 10:27:12.000
2011-08-05 10:28:04.000
2011-08-05 10:28:55.000
Using LINQ, I would like to get the following data from the column
2011-06-20
2011-08-05
So I can put into a List<>
What's the best way to do this? I already have the context stuff setup, so I don't need details on that. I just need an idea of the best "query" and logic I can use to get this data. Thanks!
You are looking for all of the Distinct dates in a range of DateTimes, the following will show examples to get what you need, given you already have them in a string or by querying your database:
Example (with list of strings):
var list; //Contains your dates
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
Example (from database table):
List<String> dates = (FROM d in datesTable
SELECT d.date.ToShortDateString()).Distinct().ToList();
Console Example to demonstrate functionality:
List<DateTime> list = new List<DateTime>();
list.Add(DateTime.Parse("2011-06-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:44:32.000"));
list.Add(DateTime.Parse("2011-04-20 11:53:32.000"));
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();
foreach (string date in result)
{
Console.WriteLine(date);
}
Console.Read();
var q = from t in mydates select distinct ( t.Date.ToShortDateString());
To select distinct dates into a list try this:
List<String> myDates = (from t in myTable
select t.myDate.ToShortDateString()
).Distinct().ToList()

lambda expression for multiple countries in Linq to Entity

I have a field called Country.
Now I have to filter the records based on the matching country.
When I have to filter the records for single country i use the lambda expression as below.
string strCountry = "USA";
var data = entities.Documents.Where(p => p.Country == strCountry);
Now I have the list of countries as below. I am wondering how to filter the records for this Contry List.
List<string> strCountry = new CacheUser().GetUserCountry();
Appreciate your responses.
Thanks
Try:
List<string> countries = ...;
var data = entities.Documents.Where(p => countries.Contains(p.Country));
This should result in an "IN" query in SQL. However, you should be aware that this may fail once you get a large number of countries in the list. I assume you can't do this with a join instead? The list of countries is only known at the client side?

How do I use Like in Linq Query?

How I can use Like query in LINQ ....
in sql for eg..
name like='apple';
thanks..
Use normal .NET methods. For example:
var query = from person in people
where person.Name.StartsWith("apple") // equivalent to LIKE 'apple%'
select person;
(Or EndsWith, or Contains.) LINQ to SQL will translate these into the appropriate SQL.
This will work in dot notation as well - there's nothing magic about query expressions:
// Will find New York
var query = cities.Where(city => city.Name.EndsWith("York"));
You need to use StartsWith, Contains or EndsWith depending on where your string can appear. For example:
var query = from c in ctx.Customers
where c.City.StartsWith("Lo")
select c;
will find all cities that start with "Lo" (e.g. London).
var query = from c in ctx.Customers
where c.City.Contains("York")
select c;
will find all cities that contain "York" (e.g. New York, Yorktown)
Source
name.contains("apple");
I use item.Contains("criteria"), but, it works efficiently only if you convert to lower both, criteria and item like this:
string criteria = txtSearchItemCriteria.Text.ToLower();
IEnumerable<Item> result = items.Where(x => x.Name.ToLower().Contains(criteria));

Get Random Rows Using JPQL

Is it possible to use JPQL for getting random rows? For example in SQL Server I would use:
select * from myTable where columnName = 4 order by newid()
Thanks,
Rod
This is what I use. I first get the number of rows for the entity and I then limit the results of the fetch query to a random row. This involves two queries, so if this is a problem for you you might want to watch native queries. If not here is the code I use:
public <T> T randomEntity(EntityManager em, Class<T> clazz) {
Query countQuery = em.createQuery("select count(id) from "+clazz.getName());
long count = (Long)countQuery.getSingleResult();
Random random = new Random();
int number = random.nextInt((int)count);
Query selectQuery = em.createQuery("from "+clazz.getName());
selectQuery.setFirstResult(number);
selectQuery.setMaxResults(1);
return (T)selectQuery.getSingleResult();
}
As of today (April 9th 2010), JPQL does not support random ordering

Resources