JPQL query for left outer join over parent vs inherited object - sql

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

Related

Query Many-to-many jpa

I need to implement SELECT with a many-to-many relationship in #QUERY. Perhaps I am misinterpreting the information written in the documentation.
My query looks like this:
#Query("select massages.id from massages join string_massage on massages.id = string_massage.massage_id where string_massage.string_id = ?1")
List<MasageEntity> findMassagesIdByStringId(#Param("strings_id") long strings_id);
In my example, I use table names. The names are underlined as an error (without compilation). Maybe I should use Entities. Then how do I do it with many-to-many relationship?
I will show a part of my Entities.
I have two Entities. MasageEntity and RstringEntity.
//MasageEntity
#Entity
#Table(name = "massages")
public class MasageEntity {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "string_text")
private String string_text;
#Column(name = "string_speed")
private Long string_speed;
#Column(name = "string_color_type")
private Long string_color_type;
#Column(name = "string_color")
private String string_color;
#Column(name = "string_timing_type")
private String string_timing_type;
#Column(name = "string_timing")
private String string_timing;
#Column(name = "showed")
private Long showed;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "string_massage",
joinColumns = { #JoinColumn(name = "massage_id") },
inverseJoinColumns = { #JoinColumn(name = "string_id") })
//RstringEntity
#Entity
#Table(name = "string")
public class RstringsEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name="code")
private String code;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
}, mappedBy = "strings")
#JsonIgnore
private Set<MasageEntity> masagess = new HashSet<>();
public RstringsEntity() {}
There are multiple ways how to perform queries in Spring Boot: native SQL and JPQL.
In case of native queries we are using pure SQL language, defining query on DB level.
In case of Java Persistence Query Language (JPQL) we define query via entity objects.
Solution 1, native queries
You created the native query in repository, but to use it we need mark it like SQL nativeQuery = true. It required for framework to understang what query laguage do you use. #Query annotation use JPQL by defult, so that's the reason of your errors.
#Repository
public interface MessageRepository extends JpaRepository<MassageEntity, Long> {
//find MessageEntities by String ID via native query
#Query(value = "select massages.* from massages join string_massage on massages.id = string_massage.massage_id where string_massage.string_id = ?1", nativeQuery = true)
List<MassageEntity> findMassagesByStringIdNativeSQL(#Param("strings_id") long strings_id);
//find Message IDs by String ID via native query
#Query(value = "select massages.id from massages join string_massage on massages.id = string_massage.massage_id where string_massage.string_id = ?1", nativeQuery = true)
List<Long> findMassagesIdByStringIdNativeSQL(#Param("strings_id") long strings_id);
}
Solution 2, JPQL queries
Example how to define JPQL queries for your case. JPQL will be translated to SQL during execution.
#Repository
public interface MessageRepository extends JpaRepository<MassageEntity, Long> {
//find MessageEntities by String ID via JPQL
#Query("select message from MassageEntity message join message.strings string where string.id = :strings_id")
List<MassageEntity> findMassagesByStringIdJPQL(#Param("strings_id") long strings_id);
//find Message IDs by String ID via JPQL
#Query("select message.id from MassageEntity message join message.strings string where string.id = :strings_id")
List<Long> findMassagesIDByStringIdJPQL(#Param("strings_id") long strings_id);
}
Native query generated by Hibernate:
select
massageent0_.id as id1_3_,
massageent0_.string_text as string_t2_3_
from
massages massageent0_
inner join
string_massage strings1_
on massageent0_.id=strings1_.massage_id
inner join
string rstringsen2_
on strings1_.string_id=rstringsen2_.id
where
rstringsen2_.id=?
Solution 3, Spring auto-generated queries
Spring can auto-generate queries by repository method definition.
Example for your case:
#Repository
public interface MessageRepository extends JpaRepository<MassageEntity, Long> {
//find MessageEntities by String ID
List<MassageEntity> findByStrings_Id(#Param("id") long strings_id);
}
Entries which I used fro sulutions:
#Entity
#Table(name = "massages")
public class MassageEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "string_text")
private String string_text;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "string_massage",
joinColumns = { #JoinColumn(name = "massage_id") },
inverseJoinColumns = { #JoinColumn(name = "string_id") })
private Set<RstringsEntity> strings = new HashSet<>();
}
#Entity
#Table(name = "string")
public class RstringsEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "code")
private String code;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
}, mappedBy = "strings")
#JsonIgnore
private Set<MassageEntity> massages = new HashSet<>();
}

could not execute query; SQL nested exception is org.hibernate.exception.SQLGrammarException: could not execute query

I have a native SQL query like this, But when I run my program and I got an Error message like my topic. But In normal SQL (without Hibernate) My query works fine..I am a new student for spring and hibernate. I really need your help.
#Query(value = "select b.bookingID,b.rentDate,b.returnDate,b.custNICNumber,b.bookingStatus,rd.lossDamage,rd.driverNICNumber,rd.vehicleRegID " +
"from booking b,bookingdetails rd where (b.bookingID=rd.bookingID) and b.bookingStatus='Rejected' && rd.vehicleRegID=?", nativeQuery = true)
Booking getReturn(String vehicleRegID);
My Booking Entity -
#AllArgsConstructor
#NoArgsConstructor
#Data
#Entity
public class Booking {
#Id
private String bookingID;
private Date rentDate;
private Date returnDate;
private String bookingStatus; //For Admin Approvel
private String rentStatus;
#ManyToOne
#JoinColumn(name = "custNICNumber", referencedColumnName = "custNICNumber")
private Customer custNICNumber;
#OneToMany(mappedBy = "bookingID")
private List<BookingDetails> bookingDetails = new ArrayList<>();
My BookignDetails Entity -
#AllArgsConstructor
#NoArgsConstructor
#Data
#Entity
public class BookingDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int bookingDetailsID;
private double lossDamage;
private String lossDamageImage;
#ManyToOne
#JsonIgnore
#JoinColumn(name = "bookingID", referencedColumnName = "bookingID")
private Booking bookingID;
#ManyToOne
#JsonIgnore
#JoinColumn(name = "vehicleRegID", referencedColumnName = "vehicleRegID")
private Vehicle vehicleRegID;
#ManyToOne
#JoinColumn(name = "driverNICNumber", referencedColumnName = "driverNICNumber",nullable = true)
private Drivers driverNICNumber;
Thank You Very Much..!
Your query uses the '&&' operator, it should be AND
b.bookingStatus='Rejected' && rd.vehicleRegID=?

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

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.

Best way to get aggregate function result inside the entity object

Many time I have to get the SQL aggregate query result inside the Entity Object itself. As of now I could able to achive the same by the following code
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = cb.createTupleQuery();
Root<Test> c = q.from(Test.class);
q.multiselect(c, cb.count(c));
q.groupBy(c.get("type"));
TypedQuery<Tuple> t = em.createQuery(q);
List<Tuple> resultList = t.getResultList();
List<Test> list = new ArrayList<>();
for(Tuple tuple : resultList){
Test te = (Test) tuple.get(0);
te.setQuantity((long)tuple.get(1));
list.add(te);
}
But I want to know what could be the best way. My Test Entity is as
#Entity
#Table(name = "test")
public class Test {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "type")
private Integer type = 0;
#Transient
private long quantity;
}
If you cannot use #Formula then I'd suggest create a database view basic on your select and mapping an additional entity to that. You can then map this to your existing entity using either as a #OneToOne or by using #SecondaryTable.
This has the added advantage of being JPA compliant (i.e. not using Hibernate's propreitary #Formula) and would look something like:
#Entity
#Table(name = "test")
public class Test {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "type")
private Integer type = 0;
#OneToOne//or via secondary table
private TestSummaryInfo summaryInfo;
public long getQuantity(){
return summaryInfo.getQuantity();
}
}
Summary mapped to a view:
#Entity
#Table(name = "vw_test_summary")
public class TestSummaryInfo {
#Id
#Column(name = "id")
private Integer id;
#Column(name = "quantity")
private Long quantity;
}

How to do a Inner-Join in JPA Criteria?

I'm using Netbeans to program a webservice REST that returns a JSON response, I am also using JPA Criteria to create the querys. I have two Entities that looks like this:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id_user")
private Integer idUser;
#Size(max = 45)
#Column(name = "username")
private String username;
#Size(max = 45)
#Column(name = "password")
private String password;
#Size(max = 45)
#Column(name = "email")
private String email;
#OneToMany(mappedBy = "idUser")
private Collection<Comment> commentCollection;
public class Comment implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id_comment")
private Integer idComment;
#Column(name = "id_thesis")
private Integer idThesis;
#Size(max = 250)
#Column(name = "comment")
private String comment;
#Column(name = "cdate")
#Temporal(TemporalType.DATE)
private Date cdate;
#JoinColumn(name = "id_user", referencedColumnName = "id_user")
#ManyToOne
private User idUser;
}
Both entities with sets and gets. I want to do a query like this:
SELECT * FROM Comments c INNER JOIN User u WHERE c.id_user = u.id_user;
but in the JPA Criteria language, I've had many problems trying to make it work but i don't get it yet.
This is the code that I'm using for the join
AbstractFacade.java
public Join<User, Comment> getCommentInfo() {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery q = cb.createQuery();
Root<User> r = q.from(User.class);
Join<User, Comment> j = r.join("commentCollection", JoinType.INNER);
Query query = getEntityManager().createQuery(q);
return (Join<User, Comment>) query.getResultList();
}
UserFacadeREST.java
#GET
#Path("test")
#Produces({"application/json"})
public Join<User, Comment> getCommentInfoREST() {
return getCommentInfo();
}
This error is shown when I test the method:
java.util.Vector cannot be cast to javax.persistence.criteria.Join
Please help me with that, I do not know if the sentence join is wrong or how to solve the cast properly.
Edit: I add the next lines to the getCommentInfo() method to see the content of the list.
q.select(j.get("username"));
List results = query.getResultList();
Iterator iter = results.iterator();
while (iter.hasNext()){
System.out.println(iter.next());
}
Error: The attribute [username] is not present in the managed type [EntityTypeImpl#1000979996:Comment.
In the case of getResultList(), the javadocs state that it returns an java.util.List (see here: http://docs.oracle.com/javaee/5/api/javax/persistence/Query.html#getResultList%28%29 ), that Vector implements.
The result type, aka what's in the list, depends on the criteria projection or, in a JPQL Query, of the from statement.
In your case, because you don't do projection, I think it should return a List<User>.
For your information, and if you are using JPA 2.0, you can also use TypedQuery which could avoid that (ugly !) cast : http://www.javabeat.net/typedquery-jpa-2/