How do I join two tables in hibernate and Spring - java

How do I join two tables in hibernate and Spring. below is my suto java code and I need to do a join on objectA where the name field is equal to the name field in objectB but I am going to be searching on ObjectA ID field but I need returned. ObjectA ID, ObjectA Name, ObjectA Regin, ObjectB Address.
//
// CLASS OBJECT A
//
#Entity
#Table(name = "tableA")
public class ObjectA {
#Id
#Column(name = "id")
private String id;
#Column(name = "name")
private String name;
#Column(name = "region")
private String region;
}
//
// CLASS OBJECT B
//
#Entity
#Table(name = "tableB")
public class ObjectB {
#Id
#Column(name = "id")
private String id;
#Column(name = "name")
private String name;
#Column(name = "address")
private String address;
}
can someone please tell me how to do this within the java code.

Add this to your A class:
#OneToOne
#JoinColumn(name="name")
private ObjectB objectB;
So that when you retrieve for A, you'll get inside corresponding B by name.

Use a cross join with a condition in the where clause to limit the join. This is the only good way (other than native sql) that i know of, to join two objects when there is no mapped relationship between them.
You can do this easily with an hql query
select a.id, a.name, a.region, b. address
from ObjectA a, ObjectB b
where a.id = b.id

You can also use inner join
select A.ID,A.Name,A.Regin,B.Address
from ObjectA as A inner join ObjectB as B

Related

JPA - How to check a conditional before in a ManyToOneRelationship

I have 2 entities, Car and Person. One person can have multiple cars. So I have
#Entity
#NoArgsConstructor
#Getter
#Table(name="Car")
public class Car {
#Id
private String id;
private String name;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "person_id")
private Person person;
}
#Entity
#NoArgsConstructor
#Getter
#Table(name="Person")
public class Person {
#Id
private String id;
private String name;
private String address;
}
However, I only want to load cars for which the owner has an address set (so it's not null).
I have tried adding
#Where(clause = "address IS NOT NULL")
but to no help.
To translate it to SQL terms, I need the query to be
SELECT * FROM car c JOIN person p ON c.person_id = p.id WHERE p.address IS NOT NULL
You have to use a Query
select c from Car c where c.person.address is not null
The #Where annotation (btw. this is a Hibernate proprietary and not a JPA annotation) is used on collections to filter the content.

Insert automatically creating and retrieving existing data in one command

i have below entities in java
#Entity
public class Person {
#Id
#GeneratedValue
private long id;
private String name;
#OneToMany(mappedBy = "person", cascade = CascadeType.ALL)
private Set<Adress> addresses;
}
#Entity
public class Address {
#Id
#GeneratedValue
private long id;
private String address;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "person_id")
private Person person;
}
so lets say i have in database one address with id = 1, now I would like to create in HQL (or SQL) an insert who would let me create a new person with address got from database with id = 1 in one command. Is it even possible? Or am i forced to do it in a few commands? I would be very gratefull for every help thank you
That's not really possible with your model as the FK for the relationship is on the address table. What you can do to reduce the overhead is this:
Person p = new Person();
entityManager.persist(p);
entityManager.createQuery("update Address a set a.person = :p where a.id = :id")
.setParameter("p", p)
.setParameter("id", 1)
.executeUpdate();

JPQL to select entity based on grandchild attribute

I am trying to select an entity A that has a B that contains a list of C where the value C.d must match a parameter.
My entities look like this:
#Entity
class A {
#GeneratedValue
#Id
private Long id;
#Column(name="B")
#OneToOne(cascade=CascadeType.ALL)
#MapsId
private B b1;
}
#Entity
class B {
#GeneratedValue
#Id
private Long id;
#OneToMany(mappedBy="b2", cascade=CascadeType.ALL)
private List<C> cs;
}
#Entity
class C {
#GeneratedValue
#Id
private Long id;
#ManyToOne
#JoinColumn(name="B")
private B b2;
private String d;
}
My naive approach on selecting my entity look like this:
SELECT entity FROM A entity WHERE entity.b1.cs.d = :d
How should the query be structured?
Should be:
SELECT entity FROM A entity INNER JOIN entity.b1.cs CSList WHERE CSList.d = :d
Read about INNER JOIN in JPA.
http://www.thejavageek.com/2014/03/24/jpa-inner-joins/
try this
TypedQuery<A> query = em.createQuery("select b.a from B b inner join C c where c.d = :d",A.class);
List<A> a = query.getResultList();

How to join Multiple tables using hibernate criteria where entity relationship is not direct?

I have three entities. those are:
#Entity
public class Organization {
#Id
private long id;
#Column
private String name;
}
#Entity
public class Book {
#Id
private Long id;
#Column
private String name;
#ManyToOne
private Organization organization;
}
#Entity
public class Account {
#Id
private Long id;
#Column
private String name;
#ManyToOne
private Book book;
}
In these three entities I would like to perform following sql:
SELECT acc.name, acc.id
FROM account acc
JOIN book b on acc.book_id = b.id
JOIN organization org on b.organization_id = org.id
WHERE org.name = 'XYZ'
In this case Account entity has no relation with the Organization entity directly. Account entity has the relation via Book. How can I achieve this using hibernate criteria dynamic query?
Another way
public List<Account> getAccountListByOrgName(String name){
return sessionFactory.getCurrentSession().createCriteria(Account.class)
.createAlias("book", "book")
.createAlias("book.organization", "organization")
.add(Restrictions.eq("organization.name", name))
.list();
}
you can do like this :
Criteria accountCriteria = getCurrentSession().createCriteria(Account.class,"acc");
Criteria bookCriteria = accountCriteria .createCriteria("book","b");
Criteria orgCriteria = bookCriteria.createCriteria("organization","org");
orgCriteria.add(Restrictions.eq("name", "XYZ"));
ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("name"));
properties.add(Projections.property("id"));
accountCriteria.setProjection(properties);
accountCriteria.list();

Eclipselink: Create objects from JOIN query

I have a SQL query
SELECT * FROM Thing AS a JOIN Thing_Property AS b ON a.id=b.Thing_ID
JOIN Property AS c ON b.properties_ID = c.id
JOIN Item AS d ON c.item_ID = d.id
ORDER BY a.name, d.name
and I Eclipselink to create my object model with it.
Here is the model:
#SuppressWarnings("serial")
#Entity
public class Thing implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private String name;
#OneToMany(cascade=CascadeType.ALL)
#PrivateOwned
private List<Property> properties = new ArrayList<Property>();
...
// getter and setter following here
}
public class Property implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private int id;
#OneToOne
private Item item;
private String value;
...
// getter and setter following here
}
public class Item implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
private int id;
private String name;
....
// getter and setter following here
}
// Code end
but I can not figure out, how to make Eclipselink create the model from that query. Can you help?
You will need to use the API EntityManager.createNativeQuery(String sqlString, Class resultClass);
entityManager.createNativeQuery("SELECT * FROM Thing AS a JOIN Thing_Property AS b ON a.id=b.Thing_ID JOIN Property AS c ON b.properties_ID = c.id JOIN Item AS d ON c.item_ID = d.id ORDER BY a.name, d.name ", Thing.class);

Categories

Resources