Select * from Table A left join Table B on A.id=B.id and A.langCode='IN';
where 'IN' is input from user.
Table A and Table B has Mapping For Id but there is no Mapping with LangCode between the two as table B dosent have an column called langCode to map with , i want to write the following query using hibernate criteria without mapping langcode.
Table: Employee :
EMP_ID - primary key ,
NAME ,
CONTACT_DETAILS
Table:Employee_Lang:
EMP_ID- composite primary key,
LANG_CODE- composite primary key,
NAME
Actual Query:
Select * from Employee Emp left outer join Employee_Lang EmpLang on Emp.EMP_ID=EmpLang.EMP_ID AND EmpLang.LANG_CODE='IN'
I have mapped only the Emp_Id as primary key from both the tables in hibernate hence hibernate criteria will only apply a join on that
And not on LangCode.
Note:-I cant change hibernate mapping and can use only hibernate Criteria , as per the clients requirement, please help me on this one.
For example you have two models:
#Entity
class Employee {
#Id
private Long id;
#OneToOne
private EmployeeLang employeeLang;
...
}
#Entity
class EmployeeLang {
#Id
private Long id;
private String langCode;
#OneToOne
private Employee employee;
...
}
You should have some mapping between them and then you can do next criteria:
Criteria criteria = session.createCriteria(Employee.class);
criteria.createAlias("employeeLang", "empLang"); // inner join with EmployeeLang
criteria.add(Restrictions.eq("empLang.langCode", "in");
List<Employee> employees = criteria.list();
Related
I have two entity classes Medicine and Medicine Group. A medicine belongs to a group . A group has more than one medicine. The relationship from medicine to group is one to one from group to medicine is one to many.
I have created the entity classes with the following properties
#Entity
public class Medicine {
#Id
String medicineId;
String medicineName;
int inStock;
String lifetimeSupply;
String lifetimeSales;
String howToUse;
String sideEffects;
//their getters and setters
}
#Entity
public class MedicineGroup {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
int groupId;
String groupName;
String groupDescription;
//their getters and setters.
}
In MySQL in the Medicine table I have a column called groupId which is a foreign key to the group table.
Normally in MySQL I could write a join statement like this
SELECT medicine_id ,medicine_name ,in_stock ,lifetime_supply, lifetime_sales, how_to_use, side_effects , group_name FROM medicine JOIN medicine_group on medicine.group_id = medicine_group.group_id;
In the above join I am able to get the group name column from the group table. How can I achieve this using JPA.
If I add a field to the medicine class like this
#OneToOne
MedicineGroup medicineGroup;
when I do a get request I get an error Unknown column 'medicine0_.medicine_group_group_id' in 'field list' . How is the field unknown yet I have a column called group_id in the medicine table?
How can I achieve a way in which if I perform a get request I get the medicine information and also the group with which it is associated with? Please help.
Simple join on the attribute:
SELECT m.medicineId ,m.medicineName ,m.inStock ,m.lifetimeSupply, m.lifetimeSales, m.howToUse, m.sideSffects , mg.groupName
FROM medicine m join m.medicineGroup mg;
and use attribute names, not column names
select m from medicine m left join fetch m.medecineGroup
I have a table Loan application whose pojo is
class LoanApplication{
int id;
int loanNo;
...
}
I have another pojo
class LoanFlow{
int id;
int loanId;
date reviewDate;
...
}
Here loanId of loanFlow is the foreign key mapped to the id of LoanApplication.
I have to fetch all the loan applications with the reviewDate.
I am trying to write a criteria like:
Criteria criteria = getSession().createCriteria(LoanApplication.class);
criteria.add(Restrictions.eq("id", someId));
How can I fetch the reviewDate also from LoanFlow with this criteria.
Criteria criteria = getSession().createCriteria(LoanApplication.class, "loApp");
criteria.createAlias("loApp.loanFlow", "flow");
criteria.add(Restrictions.eq("flow.id", 1));
You can directlly use HQL also.
using createQuery()
You can do it with subqueries, if there isn't ManyToOne or OneToMany annotations to the relationship between entities:
DetachedCriteria subQuery = DetachedCriteria.forClass(LoanFlow.class, "loanFlow");
/*Here there is a between, but you can change it to your necessity*/
subQuery.add(Restrictions.between("loanFlow.reviewDate", dateBegin, dateEnd));
subQuery.setProjection(Projections.property("loanFlow.loanId"));
Criteria criteria = getSession().createCriteria(LoanApplication.class, "loanApplication");
Subqueries.propertyIn("loanApplication.id", subQuery);
List<LoanApplication> list = criteria.list();
Scenario: Hibernate 3.6 with xml-based mapping, Java7, Postgresql 8.3.
I'm currently refactoring an application where I have got this scenario for the database:
main_table
id integer
other_field string
(id) PK
secondary_table
other_field string
value string
(other_field, value) PK
Basically, there's a secondary table which contains an "other_field" which is matched on the main table; I need to extract all values for a certain record in main_table and map them.
In SQL I'd use a query like:
SELECT value FROM secondary table INNER JOIN main_table ON secondary_table.other_field == main_table.other_field where main_table.id = 1;
But I don't understand how to map a collection of basic types (strings) to the Main object in Java using such a query (or a similar one if the one I propose is not hibernate friendly), so that I can have a "values" property on my mapped object, which should be a Set<String>
I think this is what you are looking for:
#Entity
public class Primary { // Main table
#Id
#Column(name="EMP_ID")
private long id;
...
#ElementCollection
#CollectionTable(
name="PRIMARY_SECONDARY",
joinColumns=#JoinColumn(name="PRIMARY_ID")
)
private Set<Secondary> phones;
...
}
#Embeddable
public class Secondary { // Secondary table
private String value;
...
}
Full example and further details.
I have following entities and pojo:
#Entity
public class TableA {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
string name;
}
#Entity
public class TableB {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
double price;
#ManyToOne
#JoinColumn(name = "tableAId")
TableA tableA;
//setters & getters
}
statistics
public class Statistics {
long tableAId;
double price;
long count;
public Statistics(long tableAId, double price, long count) {
this.tableAId = tableAId;
this.price = price;
this.count = count;
}
//setters & getters
}
I want to do a jpql query to get resultlist of statistics objects which is populated with reference id to tableA object and sum of price columns and count of rows in TableB table.
I've tried with following code without success:
Query query = em.createQuery("SELECT NEW se.exampel.Statistics"
+ "(b.tableAId, sum(price) ,count(b)) from TableB b ");
List<Statistics> statistics = query.getResultList();
Exception
java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: tableAId
of: se.exampel.TableB [SELECT NEW se.exampel.Statistics(b.tableAId,count(b), sum(price))
from se.exampel.TableB b ]
What am i doing wrong?
now it's fixed:
"select new se.exampel.Statistic(s.id, sum(p.price),count(p)) from tabelB p JOIN p.tabelA s GROUP BY s"
You are mixing SQL concepts into JPQL. The query needs to me made on Entity TableB, and so can only use mapped attributes within the TableB java class. So you will need to use something like:
"SELECT NEW se.exampel.Statistics(b.tableA.id, sum(b.price) ,count(b)) from TableB b "
Note that Hibernate is likely to do an inner join from tableB to tableA to get A's ID. If you want to be able to access the foreign key field in TableB directly in a JPA neutral way, you may need to add a read-only field in the TableB class for it. Something like
#Column(name="tableA_ID", insertable=false, updatable=false);
long tableAId;
which then allows you to access b.tableAId in queries:
"SELECT NEW se.exampel.Statistics(b.tableAId, sum(b.price) ,count(b)) from TableB b "
and should avoid the table join.
query should contain b.tableA which is property name instead of column name tableAId
Update: with reference to comment from #Chris query should be
SELECT NEW se.exampel.Statistics(b.tableA.id,sum(b.price),count(b)) from TableB b
I have to tables I want to map to each other.
I want to populate 2 drop down lists: code_r and code_l.
When i choose a value from code_r, code_l should display only certain records.
In my database I have 2 tables:
Table code_r
===================
CODE INT
LIBELLE VARCHAR
And
Table code_l
===================
ID BIGINT
CODE_R_ID INT
LIBELLE VARCHAR
One code_r can have multiple code_l associated with it (based on the code_r_id (not a defined as a Foreign key in the code_l definition). Of course, a code_l can only be associated to one code_r.
The following SQL query works fine:
SELECT *
FROM code_r r
left join `code_l` l on l.code_r_id = r.code;
How should I implement that using using JPA/Hibernate-3.5 annotations in the CodeR and CodeL classes??
Any help would be appreciated. Thanks in advance.
With Hibernate (and now standardized in JPA 2.0), you can use a unidirectional one-to-many association without a join table using a JoinColumn annotation:
Annotate the CodeR like this:
#Entity
public class CodeR {
#Id
private Integer code;
private String libelle;
#OneToMany
#JoinColumn(name="CODE_R_ID")
Set<CodeL> codeLs = new HashSet<CodeL>():
// getters, setters
}
And CodeL
#Entity
public class CodeL {
#Id
private Integer id;
private String libelle;
// getters, setters, equals, hashCode
}
And the JPQL query:
SELECT r FROM CodeR LEFT JOIN r.codeLs
in the CodeR class:
#OneToMany(mappedBy="code_r_id")
Collection elementsFromL;
in the CodeL class:
#ManyToOne
CodeR code_r_id;