HQL Query for Specific Nested Object in a query - java

I have a Class which has other objects as it's members fields.
e.g.:
class Orders{
private Integer code;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="code", nullable=false)
private Category category;
private PaymentType pt;
}
class Category{
private Integer id;
#OneToMany(fetch=FetchType.EAGER)
#JoinColumn(name="id", nullable=false)
private Brands brand;
....
}
class Brands{
private Integer id;
private String brandName;
}
I need to get all the Brands for that particular order.
How do I get just the brands through Orders table in Hql?

Are the relations one-to-one? If so, you should be able to query it with:
#Query("SELECT FROM Orders orders.category.brand WHERE ...")
Brands findBrandBy(...);
if you are using Spring data.

Related

Nested entities contains null after save

I have an entity with some nested entities like this
public class MyEntity {
#ManyToOne
#JoinColumn(name="FK_ENTITY2")
private Entity2 fkEntity2;
#ManyToOne
#JoinColumn(name="FK_ENTITY3")
private Entity3 fkEntity3;
}
with entity2 and entity3 like this:
public class Entity2/3{
#Id
private Long id;
#Column(name = "code")
private String code;
#Column(name = "desc")
private String desc;
//getter and setter etc
}
Both Entity2 and Entity3 have values stored in the database so when I'm doing an insert on MyEntity, I'm doing this:
#Transactional
#Service
public MyService {
//idFromController and otherIdFromController refers to existent records in the database
public MyDto save(Long idFromController, Long otherIdFromController){
Entity2 entity2 = new Entity2();
entity2.setId(idFromController);
Entity3 entity3 = new Entity3();
entity3.setId(otherIdFromController);
MyEntity newMyEntity = new MyEntity();
newMyEntity.setEntity2(entity2);
newMyEntity.setEntity3(entity3);
MyEntity result = myEntityRepository.saveAndFlush(newMyEntity);
return getDto(result);
}
}
it works fine, the data are stored correctly in the DB with the correct foreign keys BUT...
After insert I want to build a DTO which contains id, code and desc from the nested entities so something like this:
private MyDto getDto(MyEntity result){
MyDto dto = new MyDto();
dto.setId2(result.getEntity2().getId());
dto.setCode2(result.getEntity2().getCode());
dto.setDesc2(result.getEntity2().getDesc());
dto.setId3(result.getEntity3().getId());
dto.setCode3(result.getEntity3().getCode());
dto.setDesc3(result.getEntity3().getDesc());
}
Here is the problem, I only got the id fields and null on code and description.
When I call getDto() in a search it works and every field has the correct values, so it is something related to the insert transaction? how could I solve this?
When you create the DTO, the (existing) entities are not attached to the persistence context, so the corresponding data has not been loaded from the DB and cannot be copied to the DTO.
One option would be to load the entities e.g. via 'myRepository.findById...' and associate the returned (managed) entities.
you missed some part of the many-to-one relation. first in MyEntity class it was better to define a fetch type. in Entity2 and Entity3 you need to define #OneToMany as the other side of the relation with declaration of fetch type and cascade = CascadeType.ALL which simply tells to hibernate what it can do with relative entity when you are doing save, delete ,update. I reformat your code as following
public class Entity2/3{
#Id
private Long id;
#Column(name = "code")
private String code;
#Column(name = "desc")
private String desc;
#OneToMany(cascade = CascadeType.ALL,mappedBy ="fkEntity2",fetch=FetchType.LAZY)
private List<Entity2> entityTwoList;
// for Entity3
#OneToMany(cascade = CascadeType.ALL,mappedBy ="fkEntity3",fetch=FetchType.LAZY)
private List<Entity3> entityThreeList;
public class MyEntity {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="FK_ENTITY2")
private Entity2 fkEntity2;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="FK_ENTITY3")
private Entity3 fkEntity3;
}
}

Could not determine type for: java.util.List for List<String>

I am new to Spring services. I want to create a table in database which has one column with data type List.
#Entity
#Table(name = "employees")
public class Employees {
#Id
#Column(name= Id)
private long id;
#Column(name= Name)
private String name;
#Column(name= Skills)
private List<String> skills;
//getter setters for all
}
But on run I am getting error Could not determine type for: java.util.List for List
How can I resolve it? (I tried oneToMany annotation but I think I did not use it in right way)

spring data fetch mapped object in order

We have Spring Boot 2.x, Spring Data and PostgreSQL as database.
In our application we have Driver class as below
#Data
#Entity
public class Driver {
private String id;
private String name;
private String licenseNo;
}
Now a car can be driven by many drivers. So we have Car class as below.
#Data
#Entity
public class Car {
private String id;
private String number;
private String registrationNumber;
#OneToMany(fetch = FetchType.LAZY)
private List<Driver> drivers;
}
Whenever we fetch drivers from car object we get drivers not ordered by id in ascending, seems like it orders by name or id in descending order.
Is there any way in JPA where we can specify the default order by when we map.
Thanks
Hi,you add a annotation in drivers field.
show code.
#Data
#Entity
public class Car {
private String id;
private String number;
private String registrationNumber;
#javax.persistence.OrderBy("id ASC")
#OneToMany(fetch = FetchType.LAZY)
private List<Driver> drivers;
}
order option`s 'ASC' 'DESC',default is ASC
exsmple:
#javax.persistence.OrderBy("id")
#javax.persistence.OrderBy("name")
or:
#javax.persistence.OrderBy("id DESC")
#javax.persistence.OrderBy("name DESC")

Projections on nested collections

I have three entities Topic, Subject and Category. How can I prefetch id and name columns for each of the entity while retrieving all the categories with subjects and topics? I don't need other fields since it affects the performance.
#Entity
class Topic{
private Long id;
private String name;
...
//other fields
}
#Entity
class Subject{
private Long id;
private String name;
...
//other fields
#OneToMany(fetch=FetchType.LAZY)
private List<Topic> topics;
}
#Entity
class Category{
private Long id;
private String name;
...
//other fields
#OneToMany(fetch=FetchType.LAZY)
private List<Subject> subjects;
}
I would suggest creating a result class on top of the projection itself as it eases the result set handling. The ResultClass needs to have a constructor with relevant query result fields and you have to use the fully qualified name in the query itself.
select new org.mypkg.ResultClass(c.id, c.name, s.id, s.name, t.id, t.name)
from Category c
inner join c.subjects s
inner join s.topics
Then you simply:
List<ResultClass> results = em.createQuery(query).list();

org.hibernate.ObjectNotFoundException issue with using list()

The following query throws the exception:
Query query = session.createQuery("from Associate as a order by a.username asc");
associates = query.list();
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ca.mypkg.model.Associate#0]
If I create an entry in the database with id of 0 it works just fine. I don't really get it because I'm just trying to load all the entries in the db not just a specific one.
Similar questions I've found have been concerned with trying to load an object with a given ID I'm doing no such thing.
Associate class:
#Table(name = "user")
#XmlRootElement(name = "associate")
public class Associate implements Serializable {
private String username;
private String password;
private String firstName;
private String lastName;
private String userType;
private int id;
private String email;
private String isActive;
private Department dept;
private String lastUpdated;
private String associate_type;
// ...
#Id
#GeneratedValue
public int getId() {
return id;
}
#OneToOne
#JoinColumn(name = "dept")
public Department getDept() {
return dept;
}
From my experience this type of error message usually means it does not find joined entity by mentioned id, and not the entity requested in the query (Associate, in your case).
My guess is that Associate class contains a join entity which has primitive type primary key.

Categories

Resources