Select query in spring hibernate in spring mvc - mysql

Hi i am writing an spring mvc, employee application using mysql database,hibernate annotations and jsp . The database contains one table "Empdata" where empid is primary key.And there is a column "team" in "Empdata".I want to select employees in a specific team, example all the details of employees in "Team1".Here i can perform delete and edit operations in the application. For delete operation i am using
sessionfactory.getCurrentSession().createQuery("DELETE FROM Resource WHERE empid=" +resource.getEmpId()).executeUpdate();
query.I know the command line query for select is
SELECT * FROM EmpData WHERE EMPLTEAM ="Team1"
I want to know how to convert this query into hibernate?
please help,thanks in advance..

Query query = session.createQuery("from Resource where emplteam = :team");
query.setParameter("team", "Team1");
List list = query.list();
emplteam should be the property of your class Resource , not your database column's name.

I guess it is simple using HQL .
String hql = "FROM Resource E WHERE E.emplteam = team1";
Query query = session.createQuery(hql);
List results = query.list();
Hope this helps
Note: Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

have you tried using criteria api?
Criteria crit = sessionFactory.getCurrentSession()
.createCriteria(EmpData.class).add(Restrictions.eq("EMPLTEAM", "teamxxx");
List<EmpData> result = crit.list();

For example
Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Raj");
In your case i guess the Entity name is Empdata(The object that represent the table)
And the field in the object is team(That has getter and setter in object)
Query query = session.createQuery("from Empdata where team=:teamParam");
query.setParameter("teamParam", "team1");

Related

how to write hql join query

I'm new from HQL any one Please tell me how to write this Query in HQL.
My SQL Method is
public Integer validateEditDate(int id, String date);
My SQL Query is
SELECT
count(a.activity_task_id)
FROM activity_task_details AS a
JOIN milestone_activity_details AS b
ON a.milestone_activity_id = b.milestone_activity_id
WHERE a.milestone_activity_id = 17
AND DATE(a.task_end_date) > '20161229';
Where id and date is dynamic
Please convert this sql query in Hql query
To convert a SQL query in HQL you must define, as first, classes about db table mapping.
You have these two tables:
activity_task_details
milestone_activity_details
So you must have two classes, as follow:
ActivityTaskDetails
MilestoneActivityDetails
So, you must map your fields as properties. Suppose you have done this, your query will became:
SELECT
count(a.activity_task_id)
FROM ActivityTaskDetails a, MilestoneActivityDetails b
WHERE a.milestone_activity_id = b.milestone_activity_id
AND a.milestone_activity_id = :paramId
AND a.task_end_date > :paramDate;
Pay attention, if possible, your task_end_date in class ActivityTaskDetails declare as date
To execute your query:
String hql = "Your HQL query write upper";
Query q = session.createQuery(hql);
q.setString("paramId", id);
q.setDate("paramDate", date);
q.list();
session is a variable to get session factory object

Sql- how to use relational field in condition

I have three tables which is mapped like this: paymentDetails <-employee<-designation.
Now I have to get datas from paymentDetails table by particular designation of employee..
select *
from paymentDetails
where payment_date=date and employee.designation.desig_id=2;
And I am using Yii2 framework How can I achieve this in Yii2.
I get unknown column error. How to resolve this ?
$command = Yii::app()->db->createCommand()
->select(*)
->from('paymentDetails')
->where('payment_date=date')
->andWhere('employee.designation.desig_id=2')
select *
from paymentDetails
where payment_date=date and employee.designation.desig_id=2;
this will not work in SQL either, it is beacause you are using the tables employee and designation and you do not actually join them in any way.
Now you have not given us any details regarding the name of the models, but it should be something like
$paymentDetails = PaymentDetails::find()->joinWith('employee.designation')-where(['employee.designation.desig_id' => 2, 'payment_date' => 'date'])->all();
This will execute
select *
from paymentDetails JOIN employee ON 'theDefinedRelation' JOIN designation ON 'theSecondDefinedRelation' where payment_date=date and employee.designation.desig_id=2;
Anyway, it will be a long day, if you do not know why the SQL fails you have to learn SQL first.

How to do left join in doctrine with entity manager?

I have a query in sql like that
select * from films F left join ballot_films BF on F.FilmId=BF.FilmId where BF.FilmId is null;
i want to convert it into doctrine, i m new with doctrine and don't know so much, i searched and tried a lot but didn't get any success,please help me to how can i do that query in doctrine using entity managaer, million ton thanks in advance.
Assuming you have the correct mappings between films and ballot_films, the following should work:
// Get the entity manager
$em = $this->getDoctrine()->getManager("em");
// Get your film repository
$filmRepository = $em->getRepository("Film");
// Create the initial query builder
$query = $filmRepository->createQueryBuilder("films");
// Set your query criteria
$query->select("films")
->leftJoin("ballot_films")
->where("ballot_films.FilmId = null");
// Get the query results
$films = $query->getQuery()->getResult();
This will give you all films where ballot_films.FilmId is null.

JPA criteria subquery with common customerId field

How do I write the following MySQL query using JPA Criteria?
select * from deptors where customerId in
(select customerId from address where zipcode="12345-6789")
and gender="male";
I have read http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Criteria#Subquery and many stackoverflow threads including JPA 2.0, Criteria API, Subqueries, In Expressions. But I am just not getting it. Thanks for helping.
Something like:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Deptors> cq = cb.createQuery(Deptors.class);
Root<Deptors> c = cq.from(Deptors.class);
Subquery<Address> subquery = cq.subquery(Address.class);
Root<Address> a = subquery.from(Address.class);
However I would rather recommend building this query with JPQL and/or externalize it as a NamedQuery into your Entity.
Sebastian

Store procedure select all fields from One table using join

I am very frustrated from linq to sql when dealing with many to many relationship with the skip extension. It doesn't allow me to use joinned queries. Not sure it is the case for SQL server 2005 but I am currently using SQL Server 2000.
Now I consider to write a store procedure to fetch a table that is matched by two tables e.g. Album_Photo (Album->Album_Photo<-Photo) and Photo table and only want the Photos data so I match the Album's ID with Album_Photo and use that ID to match the photo. In the store procedure I am just fetch all the joinned data. After that in the linq to sql, I create a new Album object.
e.g.
var albums = (from r in result
where (modifier_id == r.ModifierID || user_id == r.UserID)
select new Album() {
Name = r.Name,
UserID = r.UserID,
ModifierID = r.ModifierID,
ID = r.ID,
DateCreated = r.DateCreated,
Description = r.Description,
Filename = r.Filename
}).AsQueryable();
I used the AsQueryable to get the result as a IQueryable rather than IEnumerable. Later I want to do something with the collection, it gives me this error:
System.InvalidOperationException: The query results cannot be enumerated more than once.
It sounds like you have a situation where the query has already executed by the time you are want to filter it later in your code.
Can you do something like...
var albums = (blah blah blah).AsQueryable().Where(filterClause) when you have enough info to process
what happens if you try albums.where(filter) later on in the code? Is this what you are trying?