jpql join without relationship cannot map to column - spring-boot

I am suing left join to join table that has no relationship
SELECT a, u.fullname FROM admin a
LEFT JOIN useru ON a.username = u.username
and return it as an List<Admin>
Admin class:
public class Admin {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
private Integer status;
#Transient
private String fullname;
}
but fullname is null

Related

How to retrieve only a specific field from child entity on #OneToOne relationship, not all fields?

When I use jpa's #OneToOne annotation, I want to get the userName field from the table, not all fields. What should I do instead?
#Setter
#Getter
#Entity
public class Menu implements Serializable {
private static final long serialVersionUID = 4462798713783196961L;
/**
* id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
#OneToOne
#JoinColumn(name = "createUserId",referencedColumnName = "userId")
private User createUser;
#Column(nullable = false)
private LocalDateTime createTime;
}
What do I need to do, can I get the userName field in the User object, but not all of it? Thank you in advance.
You can create a POJO with required fields. e.g. You only want id from Menu and userName from User:
public class CustomMenu {
private Long menuId;
private String userName;
public CustomMenu(Long menuId, String userName) {
this.menuId = menuId;
this.userName = userName;
}
// getters, setters
}
Then you can write a query with hql using the constructor in the CustomMenu with parameters new com.yourpackage.CustomMenu(m.id, m.createUser.userName) and join User entity (join m.createUser) :
TypedQuery<CustomMenu> query = entityManager.createQuery("select new com.yourpackage.CustomMenu(m.id, m.createUser.userName)"
+ "from com.yourpackage.Menu m join m.createUser", CustomMenu.class);
List<CustomMenu> menus = query.getResultList();
This generates one sql query with inner join fetching only required fields :
select menu0_.id as col_0_0_, user1_.user_name as col_1_0_ from menu menu0_ inner join user user1_ on menu0_.create_user_id=user1_.user_id

In Hibernate how to ignore associated table in selection

I am using spring boot and Hibernate and I have two tables order and orderdetails and I need two queries, first I want to select records in order along with records that relate to that order in order detail table which works fine, but when I want to select only records from order table I can't because it will bring all associated records for each order in the order detail(just like the first one). How I can select records from the order without selecting related records in order detail table?
I also tried to use #JsonIgnore annotation but it doesn't work like what I want.
My entity classes
orders
#Entity
#Setter
#Getter
public class Orders {
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "order_id")
private Long orderId;
#Column(name = "user_id")
private Long userId;
#Column(name = "user_name")
private String userName;
#Column(name = "created_date", columnDefinition = "DATE")
#JsonFormat(pattern = "MM/dd/yyyy")
private LocalDate createdDate;
private String status;
private float amount;
#Transient
String error;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name = "order_id")
private List<OrderDetail> orderDetails;
}
order detail
#Entity
#Setter
#Getter
public class OrderDetail {
public OrderDetail() {
}
public OrderDetail(Long productId, String productName, int quantity, float unitPrice, float subtotalPrice){
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.unitPrice = unitPrice;
this.subtotalPrice = subtotalPrice;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "order_detail_id", nullable = false)
Long orderDetailId;
#Column(name = "product_id")
Long productId;
#Column(name = "product_name")
String productName;
int quantity;
#Column(name = "unit_price")
float unitPrice;
#Column(name = "subtotal_price")
float subtotalPrice;
}
Queries that I tried:
#Query(value = "select orders.order_id, orders.amount, orders.created_date, orders.status, orders.user_id, " +
"orders.user_name from orders where orders.user_id = :userid", nativeQuery = true)
List<Orders> selectAllOrdersOfSpecificUser(#Param("userid") Long userId);
==================================================================================
List<Orders> findAllByUserId(Long userId);
Both of them bring all the records from the orders table and associated records in the order detail table.
FetchType.EAGER will retrive all the orderdetails as well. Use FetchType.LAZY and create a special JOIN FETCH query for getting orderdetails with orders.

Spring JPA projection with sublist

I have question about creating native query with custom response (spring projection) with nested „custom“ sublist i.e. i am trying to generate JSON output with nested sublists.
Child entity is:
#Entity
public class Child {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
#Column(nullable = false)
private String firstName;
#NotNull
#Column(nullable = false)
private String secondName;
#Enumerated(EnumType.STRING)
private Gender gender;
private Date dateOfBirth;
private String phone;
#ManyToOne
#JoinColumn(name="child_id")
private List<Parent> parents = new ArrayList<Parent>();
//...
}
Parent entity is, for example:
#Entity
public class Parent {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
#Column(nullable = false)
private String firstName;
#NotNull
#Column(nullable = false)
private String secondName;
private Date dateOfRegistration;
#OneToMany(fetch = FetchType.LAZY)
private List<Child> child = new ArrayList<Child>();
//...
}
Projection interface:
public interface ChildProjectionInterface {
public int getParentId();
public Date getFirstName();
public List<ChildResponse> getChildData();
interface ChildResponse {
public int getChildID();
public String getFirstName();
}
}
Query (but, obviously, doesn't working):
#Query(value = "SELECT p.id AS parentId, p.firstName AS firstName, c.id AS childData.childId, c.firstName AS childData.firstName FROM parent p LEFT JOIN child c ON p.child_id = c.child_id AND p.secondName = :secondName", nativeQuery = true)
List<ChildProjectionInterface> getListWithSubList(#Param(value ="secondName") String secondName);
I was reading and researching and trying..but nothing works (I saw https://medium.com/swlh/spring-data-jpa-projection-support-for-native-queries-a13cd88ec166, saw "for json auto" clause but not for spring jpa, etc.)
Did you try jpa fetch operator?
#Query("select p from parent p left join fetch p.child c where p.secondName = :secondName")

Jpa-Jpql Query to Select All field from parent Entity and specific field from child Entity in OneToOneMapping

I have oneToOne RelationShip between Employee and student entity i want to fetch all field from Employee Entity and name and modelNumber From Laptop Entity
Employee Entity
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "employee_name")
private String name;
#Column(name = "date_of_birth")
private String dob;
#Column(name = "gender")
private char gender;
#Column(name = "skills")
private String[] skills;
#OneToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
#JoinColumn(name = "laptop_id")
private Laptop laptop;
//getter setter
Laptop Entity
#Entity
public class Laptop {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String ram;
private String modelNumber;
private String processor;
//getter Setter
select e.id, e.name, e.dob, e.gender, e.skills,
e.laptop.name, e.laptop.modelNumber
from Employee e
Please start by reading the docs: https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#hql

Spring Specification dynamic query join

I have two entity:
#Entity
public class User{
#Id
private String id;
...
private String username;
private String customerId;
}
public class Customer{
#Id
private String id;
private String name;
}
How can I create dynamic query just like:
select * from user where username='...';
select * from user u left join customer c o u.customerId=c.id where c.name='...';
and without #OneToOne?

Resources