Hibernate - select entity with id from another table? - java

I have two tables. Property name and column name in brackets.
Table Animal has fields:
animalId (animal_id), name (name), owner (owner_id)
owner is many to one relationship to owner object and owner_id column
Table Owner has fields:
ownerId (owner_id), name
I want to select an the owner of animal who has id 5. How can that be done with hibernate?

You haven't provided much, but from what you're asking for.. this should work
Query q = sess.createQuery(" select o.owner from animal as o where o.animalId = 5")

Related

Spring Data JPA join 2 tables

I have 2 tables in MySQL database: user and user_additional_details with columns described below.
User
id (auto increment)
userId (unique)
first name
last name
phone
email
User Additional Details
id (auto increment)
userId (matches userId in User)
personalPhone
personalEmail
Table user_additional_details contains 0 or 1 row for each userId in user table.
However, database does not have a foreign key constraint defined. Ideally, columns from user_additional_details should have been added as nullable columns in user table, but that was not done for some unknown reason. Now I need to define the entity for following query.
select user.userId, user.phone, user_a_d.personalPhone
from user
join user_additional_details as user_a_d
on user.userId = user_additional_details.userId
I tried defining JPA entities for the tables, but not able to figure out how to create an entity that uses columns from different tables.
It seems like the SecondaryTable annotation is what you are looking for
Specifies a secondary table for the annotated entity class. Specifying
one or more secondary tables indicates that the data for the entity
class is stored across multiple tables.
Here you find a detailed example of how to use it - http://www.thejavageek.com/2014/09/18/jpa-secondarytable-annotation-example/
Create UserEntity (with all the columns from User table) and UserAdditionalDetailsEntity(with all the columns from user_additional_details table). I assume you are aware how to create JPA entities and map them to database table.
I hope you would have create entity manager factory object in your spring configuration file. With the help of that create entity manager object .
Once EntutyManager Object is created:
Query q= em.createQuery("select user.userId, user.phone, userDetails.personalPhone
from UserEntity user
join UserAdditionalDetailsEntity as userDetails
on user.userId = userDetails.userId");
List<Object[]> resultList= q.getResultList();
Once you get resultList you can iterate over the list of object array and get data.
Each index of the resultList will contain the object array representing one row
Keep in mind that field name mentioned in query should be same as the one mentioned in your JPA Entites.

Spring framework data JPA Inner Join on multiple columns

I would like to do the following query using spring jpa. I am able to build the where clause for my statement with Predicate.toPredicate. However, I don't know how to join on more than one column. On a single column it can be done in the repository using #Query and #Param
SELECT a.name, a.column_x, b.column_y
FROM table_a a
INNER JOIN table_b b
ON b.name = a.name
AND b.pk_2 = a.pk_2
AND b.pk_3 = a.pk_3
WHERE ...;
Another question I have is, is an intermediate tableA_tableB association beneficial if I have something like this, oneToMany relations.
Table 1: thing
thing_name
type
tenant
other1
other2
Table 2: thing_sub_prop
prop_name
value
Association table: thing_thing_sub_prop
type
thing_name
tenant
prop_name
value
Or is it better to just have two tables, thing and thing_sub_prop with the primary key columns of thing repeated in thing_sub_prop as a foreign key?

Returning child entities from a parent entity with JPA join

How can I return a list of entities that has a relationship to a parent in JPA?
I have a User entity that has a #OneToMany mapping on a property named pets. The child entities are of type Pet. It is only a uni-directional relationship.
How can I write a join in JPA that returns all pets given a user?
So you have a couple of options.
You can use the following annotations:
#ManyToOne
#JoinColumn
This is how you would use it.
public class User
{
// your standard fields / columns in database
#OneToMany (Fetch can be of eager/ lazy)
#JoinColumn (name="column to join on", referencedColumnName="column to join on in parent class")
private List<Pet> pets;
}
public Class Pet
{
//data fields
}
What essentially happens is the list of pets is populated when you are querying for the user object.
Using JPA to Query the DB.
So i am guessing that Your user would have some sort of id and the pet table would have some sort of Id to the user that are linked.
So we would do the following
Select * from user where user_id = ?;
this will essentially give you the user object
Select * from pet where owner_user_id = ?
this will essentially give you all the pets that belong to that user.
Then you can populate your object yourself.
I am not 100% sure of how your table looks like, but I was hoping to give it a stab from just what I would do point of view.

Hibernate: mapping many-to-one association to different parent table depending on type?

I have tables which look like this:
Item table:
ItemName Varchar2(200)
ItemId Number
OwnerId Number
OwnerType number
Person table:
PersonName Varchar2(200)
PersonId Number
Company table:
CompanyName Varchar2(200)
CompanyId Number
When the ownerType for an Item is '1', the ownerId of the item is a foreign key PersonId of the 'person' table. When the OwnerType is '2', the ownerId is a foreign key of the CompanyId of the Company table.
I didn't do the data modelling & I don't have the option of changing the schema.
I'd like to solve two problems:
(1) I'd like a mapping file for the Item table which would give me the items's owner.
(2) I'd like mapping files for the Person & Company tables which would give me the Items owned by the Person or Company, respectively.
Note: a CompanyId and a PersonId can be the same number, so an item is only owned by a Person when person.personid = item.ownerid and item.ownertype = 1.
I can control the mapping files & the object diagram, so I could create an Owner interface or super-class.
Can Hibernate do this sort of thing?
Case 1: you can use the concept of Table per class hierarchy.
Case 2: map items as set for person/company class with where
condition on the set mapping.

JPA Query optimization by avoiding JOIN to lookup table?

Imagine a table emp:
CREATE TABLE emp
( id NUMBER
, name VARCHAR
, dept_code VARCHAR
)
and a table dept:
CREATE TABLE dept
( code VARCHAR
, name VARCHAR
)
emp.dept_code references dept.code as a ForeignKey.
These tables are mapped to JPA Entities, and the ForeignKey is modeled as an association:
#ManyToOne
#JoinColumn(name = "dept_code")
private Department department;
Given following data:
emp dept
---------------- ------------------
1 John SALS SALS Sales
2 Louis SALS SUPT Support
3 Jack SUPT
4 Lucy SUPT
I would like to write a JPA query that returns all Emloyees in the Support Department. Assume I know the PrimaryKey of the Support Department (SUPT)
I guess that would be:
SELECT emp
FROM Employee emp JOIN emp.department dept
WHERE dept.code = 'SUPT'
Question:
As the Department key SUPT code is available in the emp table, is there a way to rewrite the JPA query by avoiding the JOIN to the Department Entity?
Would this result in a performance improvement? Or is a JPA implementation (like Hibernate) smart enough to avoid the database join to the dept table?
You would usually write the query as
select emp
from employee emp
where emp.department.code = 'SUPT'
and let your provider figure out the best way to come up with the result. In the case of hibernate, yes, it is smart enough to realize it can just look at the join column.
edit : It is worth noting, that you haven't set up lazy loading in your annotations, so it's going to join the table in to create the department entity anyway :)

Categories