Spring Data Rest Left Outer Join non-Entity POJO Null Entity Error - sql

How do i accomplish getting the this interface method to work? i am using a MySQL DB if that matters...
public interface PersonRoleRepository extends CrudRepository<PersonRole,Long>{
//This causes null entity error from hibernate even though the SQL works outside hibernate
#Query(value="select * from Role r left outer join Person_Role pr on r.id = pr.role_id and pr.person_id = ? order by pr.expires_date desc", nativeQuery = true)
List<PersonRoleDto> getAllRolesAndPersonsStatusWithEachRole(int personId);
}
Here is the SQL query that returns what i want in SQL Workbench...
Select r.*, pr.*
from
Role r
left outer join person_role pr on r.id = pr.role_id and pr.person_id = ?
order by pr.expires_date desc;
Important MySQL database structure...
Table: Role
role_id bigint
name varchar
description varchar
...
Table: Person
person_id bigint
first_name varchar
last_name varchar
...
Table Person_Role_Link
person_role_id bigint
role_id bigint
person_id bigint
...
alter table person_Role_Link add constraint l1 foreign key (person_id) references Person(person_id)
alter table person_Role_Link add constraint l2 foreign key (role_id) references Role(role_id)
Here is the entity info...
#Entity
#Table(name="Role")
#EntityListeners(AuditEntityListener.class)
public class Role extends AbstractAuditEntity {
private static final long serialVersionUID= 44543543543543454543543L;
#id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="role_id")
private long id;
#NotNull
private String fullName
...
#OneToMany(mappedBy="role",cascade=CascadeType.ALL)
private Set<PersonRole> personRoles = new HashSet<>();
...
}
#Entity
#Table(name="Person_Role_Link")
#EntityListeners(AuditEntityListener.class)
class PersonRole extends AbstractAuditEntry{
private static final long serialVersion = 54324243242432423L;
#id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="person_role_id")
private long id;
#ManyToOne
#JoinColumn(name="person_id")
private Person person;
#ManyToOne
#JoinColumn(name="role_id")
private Role role;
...
}
#Entity
#Table(name="Person")
#EntityListeners(AuditEntityListener.class)
public class Person extends AbstractAuditEntity{
private ... serialVersionUID...;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="person_id")
private Long id;
...
#OneToMany(mappedBy="person", cascade=CascadeType.ALL)
private Set<PersonRole> personRoles = new HashSet<>();
...
}
Just for now i made a simple interface...
public interface PersonRoleDto {
String getFullName();
String getDescription();
//i want more attributes but for now i will just see if it works with the basics
}
Here is the latest HQL i tried...
public interface PersonRoleRepository extends CrudRepository<PersonRole,Long>{
//PersistentEntity must not be null
#Query("select r.fullName as fullName, r.description as description from Role r left join r.personRoles pr where pr.person = :person")
List<PersonRoleDto> findAllRolesWithPersonsStatus(#Param("person") Person person);
...
}
Whether I use HQL or native SQL i get a null entity error from hibernate. Also, the SQL generated from the HQL works without error but i still get a null entity error in code and, second, the SQL generated from HQL is slightly off which makes the results off. That's why i was trying so hard to get the native SQL to work.
The relationship is used to figure out how many people are in a role and at other times what roles a person has. This is a circular relationship, i'd say. I work on an Intranet so i had to hand type everything. If there are any problems seen in my code other than with the stated native query as stated then it is most likely because i had to hand type everything and not because the code is buggy. Everything else works so far but this one thing.
All help is appreciated.
UPDATE!!!!
I think this is the answer to my problem but when i try it i still get the error: PersistentEntity must not be null!
Here is how i tried to set it up...
//Added this to the top of PersonRole entity
#SqlResultSetMapping(
name="allRolesAndPersonsStatusWithEachRole"
classes={
#ConstructorResult(
targetClass=PersonRoleStatus.class,
columns={
#ColumnResult(name="full_name"),
#ColumnResult(name="description"),
...
}
)
}
)
#NamedNativeQuery(name="PersonRole.getAllRolesAndPersonsStatusWithEachRole",
query="Select r.*, pr.* from Role r Left Join person_role_link on r.role_id = pr.role_id and pr.person_id = :id", resultSetMapping="allRolesAndPersonsStatusWithEachRole")
Created my DTO like this...
public class RolePersonStatus {
private String fullName;
private String description;
private String ...
public RolePersonStatus(String fullName, String description, ...){
this.fullName = fullName;
this.description = description;
...
}
}
In my repository i just have:
//No annotation because it stated that the name of the method just needed to match the native query name?!?!?
List<RolePersonStatus> findAllRolesWithPersonStatus(#Param("id" Long id);
What am i missing???????

Try this way:
Entities
#Entity
#Table(name = "parents")
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#OneToMany
private List<Child> children = new ArrayList<>();
//...
}
#Entity
#Table(name = "children")
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#ManyToOne(optional = false)
private Reference reference;
#OneToMany
private final List<Toy> toys = new ArrayList<>();
//...
}
#Entity
#Table(name = "references")
public class Reference {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
//...
}
#Entity
#Table(name = "toys")
public class Toy {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
//...
}
DTO
public interface DemoDto {
String getParentName();
String getChildName();
String getToyName();
String getDescription();
}
Repository
public interface ParentRepo extends JpaRepository<Parent, Long> {
#Query("select " +
"p.name as parentName, " +
"c.name as childName, " +
"t.name as toyName, " +
"r.description as description " +
"from " +
"Parent p " +
"join p.children c " +
"join c.reference r " +
"join c.toys t " +
"where c.id = ?1 " +
"order by r.description desc")
List<DemoDto> getDto(Long childId);
}
Usage
#RunWith(SpringRunner.class)
#SpringBootTest
public class ParentRepoTest {
#Autowired
private ParentRepo parentRepo;
#Test
public void getDto() throws Exception {
List<DemoDto> dtos = parentRepo.getDto(3L);
dtos.forEach(System.out::println);
}
}
Result
{parentName=parent2, toyName=Toy7, childName=child3, description=Description1}
{parentName=parent2, toyName=Toy8, childName=child3, description=Description1}
{parentName=parent2, toyName=Toy9, childName=child3, description=Description1}
More info is here.
Working example.

Related

How to include additional data in one entity from other tables (via joins or subqueries) and still have it be insertable/updatable?

So I have the following code working correctly on my ecommerce site.
#Entity
#Table(name = "v_customer_wishlist")
#NamedQuery(name = "VCustomerWishlist.findAll", query = "SELECT w FROM VCustomerWishlist w")
public class VCustomerWishlist implements Serializable {
#Id
#Column(name = "cart_id")
private int _cartId;
//get/set methods
...
#OneToMany(mappedBy = "_wishlist", cascade = CascadeType.ALL)
private List<VCustomerWishlistItem> _items;
//get/set methods
}
#Entity
#Table(name = "v_customer_wishlist_items")
#NamedQuery(name = "VCustomerWishlistItem.findAll", query = "SELECT i FROM VCustomerWishlistItem i")
public class VCustomerWishlistItem implements Serializable {
...
public VCustomerWishlistItem(int cartId, int productId) {
VCustomerWishlistItemPK id = new VCustomerWishlistItemPK (cartId, productId);
setId(id);
}
#EmbeddedId
private VCustomerWishlistItemPK id; //is PK for cartId and productId
//get/set methods
...
#ManyToOne
#JoinColumn(name = "cart_id")
private VCustomerWishlist _wishlist;
//get/set methods
...
#Column(name = "product_name")
private String _productName;
//get/set methods
...
}
Then somewhere in my backing bean, I could do somethin like this (simplified version):
...
VCustomerWishlist wishlist = getCustomer().getWishlistById(cartId);
...
VCustomerWishlistItem item = new VCustomerWishlistItem(wishlist.getId(), product.getId());
...
item.setSequenceNum(wishlist.getItems().size()+1);
item.setProductName(product.getName());
item.setQuantity(1);
wishlist.addItem(item);
wishlistItemService.save(item);
...
So I can add items (product references) to wishlist and JPA will correctly generate the INSERT INTO queries and so forth.
However, upon thinking about it, I thought it would be better to retrieve this data directly from my 'master_products' table instead of what was stored in the VCustomerWishlistItem.
This way I would always have the most up-to-date productName, unitPrice and so forth for wishlist items saved weeks or months before.
The thing is, if I modify the view in my database to include this additional info by adding joins or subqueries; as soon as add joins or subqueries to my view, it becomes non-inserable/updatable.
I thought that it could be done via JPLQ in one #NamedQuery definition, but I understand these are designed to be used manually when retrieving desired sets. As opposed to the nice built-in way that JPA automatically retrieves the wishlist.items resolving it with the indicating annotation properties.
The fantasy property would be one where I can specify a direct table source for the entity, ignoring the join and subquery tables.
So for example, if the source for 'v_customer_wishlist_items_readonly' was:
SELECT
`cwi`.`cart_id` AS `cart_id`,
`cwi`.`product_id` AS `product_id`,
`cwi`.`sequence_num` AS `sequence_num`,
`mp_readonly`.`product_name` AS `product_name`,
`mp_readonly`.`product_web_id` AS `product_web_id`,
`mp_readonly`.`unit_price` AS `unit_price`,
`cwi`.`quantity` AS `quantity`,
`mp_readonly`.`unit_price`*`csci`.`quantity` AS `item_subtotal`,
`cwi`.`create_datetime` AS `create_datetime`,
`cwi`.`update_datetime` AS `update_datetime`
FROM
`customer_wishlist_items` `cwi` JOIN `master_products` `mp_readonly` ON `cwi`.`product_id` = `mp_readonly`.`product_id`
ORDER BY `cwi`.`sequence_num`;
It would be ideal to have a an annotation where I could indicate that primary table name is 'customer_wishlist_items', so all updates/inserts would only apply to this table and changes to the rest of the read-only fields would be ignored.
So somethint like this:
#Entity
#Table(name = "v_customer_wishlist_items_readonly")
#PrimaryTable(name = "customer_wishlist_items") //fantasy annotation
#NamedQuery(name = "VCustomerWishlistItem.findAll", query = "SELECT s FROM VCustomerWishlistItem s")
public class VCustomerWishlistItem implements Serializable {
...
Does anyone know what would be the correct way of implementing this?
Thanks a lot in advance!
Why not use derived ids or the MapsId to let JPA set your foreign key/id columns for you?
#Entity
#Table(name = "v_customer_wishlist_items")
#NamedQuery(name = "VCustomerWishlistItem.findAll", query = "SELECT i FROM VCustomerWishlistItem i")
public class VCustomerWishlistItem implements Serializable {
...
public VCustomerWishlistItem(VCustomerWishlist cart, Product product) {
this._wishList = cart;
this._product = product;
setId(new VCustomerWishlistItemPK());//JPA will populate this for you
}
#EmbeddedId
private VCustomerWishlistItemPK id; //is PK for cartId and productId
//get/set methods
...
#ManyToOne
#MapsId("cartId")
#JoinColumn(name = "cart_id")
private VCustomerWishlist _wishlist;
//get/set methods
...
#MapsId("productId")
#JoinColumn(name = "product_id")
private Product _product;
//get/set methods
...
}
With this, you don't need to have or lookup the cartId/productId values at all as JPA will figure them out and set them for you, allowing you do just use code like:
VCustomerWishlistItem item = new VCustomerWishlistItem(wishlist, product);
...
item.setSequenceNum(wishlist.getItems().size()+1);
item.setQuantity(1);
wishlist.addItem(item);
wishlistItemService.save(item);
You should probably just set the sequenceNum and add the item to the wishlist in the item constructor, though I'm not a fan this approach to sequencing as it can lead to concurrency issues and problems maintaining it.
You can also do away with the EmbeddedId if you don't need it within your entity and use it as a primary key class; you'd just have to change the property names within it to match the relationships names from the entity:
#Entity
#IdClass(VCustomerWishlistItemPK.class)
#Table(name = "v_customer_wishlist_items")
#NamedQuery(name = "VCustomerWishlistItem.findAll", query = "SELECT i FROM VCustomerWishlistItem i")
public class VCustomerWishlistItem implements Serializable {
...
public VCustomerWishlistItem(VCustomerWishlist cart, Product product) {
this._wishList = cart;
this._product = product;
}
...
#ManyToOne
#Id
#JoinColumn(name = "cart_id")
private VCustomerWishlist _wishlist;
//get/set methods
...
#Id
#JoinColumn(name = "product_id")
private Product _product;
//get/set methods
...
}
The primary key class might then look like:
public class VCustomerWishlistItemPK {
public Integer _product;
public Integer _wishlist;
//optional getter/setter methods..
}
The properties within the ID class must match the names of the properties in your entities, but use the type of the primary key from the referenced class.

(N + 1) selects problem with child Map-collection

friends! I have these entities:
Document:
#Entity
#Table(name = "documents")
public class Document extends AbstractNamedEntity {
....
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "document_change_notices",
joinColumns = #JoinColumn(name = "document_id"),
inverseJoinColumns = #JoinColumn(name = "change_notice_id"))
#MapKeyColumn(name = "change")
private Map<Integer, ChangeNotice> changeNotices;
....
}
and ChangeNotice:
#Entity
#Table(name="change_notices")
public class ChangeNotice extends AbstractNamedEntity {
....
#ElementCollection(fetch = FetchType.LAZY)
#CollectionTable(name = "document_change_notices", joinColumns = #JoinColumn(name = "change_notice_id"))
#MapKeyJoinColumn(name = "document_id")
#Column(name = "change")
private Map<Document, Integer> documents;
....
}
And these are my repositories:
For Document:
public interface DocumentRepository extends JpaRepository<Document, Integer> {
....
#Query("select d from Document d left join fetch d.changeNotices where d.decimalNumber=:decimalNumber")
Optional<Document> findByDecimalNumberWithChangeNotices(#Param("decimalNumber") String decimalNumber);
....
}
and for ChangeNotice:
public interface ChangeNoticeRepository extends JpaRepository<ChangeNotice, Integer> {
....
#Query("select c from ChangeNotice c left join fetch c.documents where c.id=:id")
Optional<ChangeNotice> findByIdWithDocuments(#Param("id") int id);
....
}
So, when i want to get Document with changeNotices, thats not a problem, i have only one select.
But when i want to get ChangeNotice with documents - i have (n + 1), first for document, and n for changeNotices Map.
I use join fetch in my query, but it does not help.
I think the problem is that in Document i have Map<K,V>, where entity is a value, and i should use #ManyToMany relationship. And in ChangeNotice i have Map<K,V>, where entity is a key, and i should use #ElementCollection.
Are there any ways to write a query that select ChangeNotice with documents in one select? (without changing my entities code, may be small fixes possible)
So, a lot of time has passed, i didn't find an answer. But it is my architecture issue. I had to use another class, that contains Document, ChangeNotice, and Integer field. My Document and ChangeNotice entities had child collection of this class with #OnetoMany relationship. It solves the problem.

Spring Data Rest: JOIN search by parent column is throwing error (o.s.d.r.w.RepositoryRestExceptionHandler : PersistentEntity must not be null!)

I am using Spring Data Rest for a Department-Employee relationship as shown below, and have a RepositoryRestResource defined on Employee.
class Department {
#Id
UUID Id;
String name;
#OneToMany(mappedBy = "employee", targetEntity = Employee.class, cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
#RestResource(exported = false)
private Set<Employee> employees;
}
class Employee {
#Id
UUID Id;
String firstName;
String lastName;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "dept_ref")
#RestResource(exported = false)
private Department department;
}
#Projection(name = "employeeProjection", types = {Employee.class})
interface EmployeeProjection {
String getFirstName();
String getLastName();
}
#RepositoryRestResource(excerptProjection = EmployeeProjection.class)
public interface EmployeeRepository extends CrudRepository<Employee, UUID> {
//this doesn't work
#Query(value = "SELECT emp.firstName as firstName , emp.lastName as lastName FROM Employee emp JOIN emp.department "
+ "WHERE emp.department.name = :departmentName ")
List<EmployeeProjection> findByDepartmentName(#Param("departmentName") String departmentName);
//this works
List<EmployeeProjection> findByFirstName(#Param("firstName") String firstName);
}
Issue is when I perform a join search as findByDepartmentName, I am getting below error.
2019-07-01 00:26:33.300 ERROR 7396 --- [nio-8443-exec-5] o.s.d.r.w.RepositoryRestExceptionHandler : PersistentEntity must not be null!
java.lang.IllegalArgumentException: PersistentEntity must not be null!
at org.springframework.util.Assert.notNull(Assert.java:134)
at org.springframework.data.rest.webmvc.PersistentEntityResource$Builder.<init>(PersistentEntityResource.java:140)
the issue got resolved by changing the return type to List<Employee> from List<EmployeeProjection>, also it still returns me the projection as its an excerptProjection. not sure why the Spring Data Rest expects this but it works.
List<Employee> findByDepartmentName(#Param("departmentName") String departmentName);

JPQL query for left outer join over parent vs inherited object

Entities/Model:
#Inheritance(strategy=InheritanceType.JOINED)
public class UserAccount implements CommonUserAccount {
#Id
private Long id;
private String email;
#Embedded
private PersonalInfo personalInfo = new PersonalInfo(); // name/surname - regular stuff
#ElementCollection
#CollectionTable(name = "UserAccountTags", joinColumns = #JoinColumn(name = "accountId", nullable = false))
#Column(name = "tag")
//#Transient
private Set<String> tags = new HashSet<String>();
#ElementCollection
#CollectionTable(name = "UserAccountRoles", joinColumns = #JoinColumn(name = "accountId", nullable = false))
#Enumerated(EnumType.STRING)
#Column(name = "userRole")
private Set<UserAccountRole> userRoles = new HashSet<UserAccountRole>();
// regular getters/setters
}
#Entity
#Table
#PrimaryKeyJoinColumn(name = "useraccountid")
public class DemoUserAccount extends UserAccount implements CommonUserAccount {
#Column
private String passwordHash;
#Column
private Long failedLogins;
#Column
#Temporal(TemporalType.TIMESTAMP)
Date lockedAt;
// regular getters/setters
}
Question:
Is it possible to build query using JPQL (for JPA2.0) that would return DemoUserAccounts joined on parent table - UserAccounts? Doing this would assume I can filter on tags/user_roles as well. In general some records will not have DemoUserAccount specific fields filled in.
When you do a SELECT from DemoUserAccount, you already have the UserAccount fields available to do a query using them.
So, if you want to filter by email and failedLogins:
SELECT d FROM DemoUserAccount d WHERE d.email = 'you#you.com' AND d.failedLogins > 3

JPA select query on ManyToMany

Can anybody help me with SELECT query on this ManyToMany connection? I want to select enrolled users specified by id of user in my EJB class.
Course entity snippet
Public class Course implements Serializable {
...
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#ManyToMany
#JoinTable(name="course_user", joinColumns={#JoinColumn(name="course_id", referencedColumnName="id")},
inverseJoinColumns={#JoinColumn(name="user_id", referencedColumnName="id")})
private List<User> enrolledStudents;
...
User Entity snippet
public class User implements Serializable {
private static final long serialVersionUID = 1L;
...
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#ManyToMany(mappedBy="enrolledStudents")
private List<Course> enrolledCourses;
...
For example this is my another select query in EJB, but it is not on ManyToMany. I want something similar, but can not figure out how..
public List<Course> findOwndedCourses(long id) {
TypedQuery<Course> query = entityManager.createQuery("SELECT c FROM Course c WHERE c.owner.id = :ownerId", Course.class);
query.setParameter("ownerId", id);
return query.getResultList();
}
Thank you for help guys!!
This query should do it:
select c FROM Course c JOIN c.enrolledStudents u WHERE u.id = :userId
or this one may be simpler (the join is implicit):
FROM Course c WHERE c.enrolledStudents.id = :userId