Generic querydsl orderBy dynamic path generation with left joins - java

I've run into a problem while using JPA with Querydsl and Hibernate for data storage management. The sample model is as follows:
#Entity
public class User {
....
#ManyToOne
#JoinColumn(name = "CATEGORY_ID")
private Category category;
}
#Entity
public class Category {
..
private String acronym;
#OneToMany(mappedBy = "category")
List<User> userList;
}
In my Spring MVC webapp I have a search form with User parameters and orderBy select. The orderBy select can be either User property or Category property. The orderBy parameters are stored as Map (f.e. {"login" : "adm", {"firstName" : "John"}. The search function receives the search parameters (as string) and the map above with order specification. The simplified code for ordering is as follows:
Map<String, String> orderByMap = new HashMap<String, String>();
orderByMap.put("firstName", "asc");
orderByMap.put("unit.acronym", "desc");
PathBuilder<User> pbu = new PathBuilder<User>(User.class, "user");
....
for (Map.Entry<String, String> order : orderByMap.entrySet())
{
// for simplicity I've omitted asc/desc chooser
query.orderBy(pbu.getString(order.getKey()).asc());
}
The problem starts when I want to introduce sorting by Category's parameter, like {"category.acronym", "desc"}. As explained here, the above code will make querydsl to use cross join with Category table and omitt the Users without Categories, which is not expected behavior.
I know, I have to introduce the left join with Categories and use the alias for the sorting to make it work, hovewer I'm looking for efficient way to do it dynamically. Stripping each String looking for category or any other entity (like "user.category.subcategory.propetry") will introduce a lot of ugly code and I'd rather not do that.
I'd appreciate the help with some more elegant solution.

I added now a protoype of the implementation to the test side of Querydsl https://github.com/mysema/querydsl/issues/582
I will consider a direct integration into Querydsl if this a common use case
public class OrderHelper {
private static final Pattern DOT = Pattern.compile("\\.");
public static PathBuilder<?> join(JPACommonQuery<?> query, PathBuilder<?> builder, Map<String, PathBuilder<?>> joins, String path) {
PathBuilder<?> rv = joins.get(path);
if (rv == null) {
if (path.contains(".")) {
String[] tokens = DOT.split(path);
String[] parent = new String[tokens.length - 1];
System.arraycopy(tokens, 0, parent, 0, tokens.length - 1);
String parentKey = StringUtils.join(parent, ".");
builder = join(query, builder, joins, parentKey);
rv = new PathBuilder(Object.class, StringUtils.join(tokens, "_"));
query.leftJoin((EntityPath)builder.get(tokens[tokens.length - 1]), rv);
} else {
rv = new PathBuilder(Object.class, path);
query.leftJoin((EntityPath)builder.get(path), rv);
}
joins.put(path, rv);
}
return rv;
}
public static void orderBy(JPACommonQuery<?> query, EntityPath<?> entity, List<String> order) {
PathBuilder<?> builder = new PathBuilder(entity.getType(), entity.getMetadata());
Map<String, PathBuilder<?>> joins = Maps.newHashMap();
for (String entry : order) {
String[] tokens = DOT.split(entry);
if (tokens.length > 1) {
String[] parent = new String[tokens.length - 1];
System.arraycopy(tokens, 0, parent, 0, tokens.length - 1);
PathBuilder<?> parentAlias = join(query, builder, joins, StringUtils.join(parent, "."));
query.orderBy(parentAlias.getString(tokens[tokens.length - 1]).asc());
} else {
query.orderBy(builder.getString(tokens[0]).asc());
}
}
}
}

Related

How to dynamic search with Criteria API in Java?

I want to dynamic search with Criteria API in Java.
In the code I wrote, we need to write each entity in the url bar in JSON. I don't want to write "plaka".
The URL : <localhost:8080/api/city/query?city=Ankara&plaka=> I want to only "city" or "plaka"
Here we need to write each entity, even if we are going to search with only 1 entity. Type Entity and it should be empty.
My code is as below. Suppose there is more than one entity, what I want to do is to search using a single entity it wants to search. As you can see in the photo, I don't want to write an entity that I don't need. can you help me what should I do?
My code in Repository
public interface CityRepository extends JpaRepository<City, Integer> , JpaSpecificationExecutor<City> {
}
My code in Service
#Service
public class CityServiceImp implements CityService{
private static final String CITY = "city";
private static final String PLAKA = "plaka";
#Override
public List<City> findCityByNameAndPlaka(String cityName, int plaka) {
GenericSpecification genericSpecification = new GenericSpecification<City>();
if (!cityName.equals("_"))
genericSpecification.add(new SearchCriteria(CITY,cityName, SearchOperation.EQUAL));
if (plaka != -1)
genericSpecification.add(new SearchCriteria(PLAKA,plaka, SearchOperation.EQUAL));
return cityDao.findAll(genericSpecification);
}
#Autowired
CityRepository cityDao;
My code in Controller
#RestController
#RequestMapping("api/city")
public class CityController {
#Autowired
private final CityService cityService;
public CityController(CityService cityService) {
this.cityService = cityService;
#GetMapping("/query")
public List<City> query(#RequestParam String city, #RequestParam String plaka){
String c = city;
int p;
if (city.length() == 0)
c = "_";
if (plaka.length() == 0) {
p = -1;
}
else
p = Integer.parseInt(plaka);
return cityService.findCityByNameAndPlaka(c,p);
}
My code in SearchCriteria
public class SearchCriteria {
private String key;
private Object value;
private SearchOperation operation;
public SearchCriteria(String key, Object value, SearchOperation operation) {
this.key = key;
this.value = value;
this.operation = operation;
}
public String getKey() {
return key;
}
public Object getValue() {
return value;
}
public SearchOperation getOperation() {
return operation;
}
My code in GenericSpecification
public class GenericSpecification<T> implements Specification<T> {
private List<SearchCriteria> list;
public GenericSpecification() {
this.list = new ArrayList<>();
}
public void add(SearchCriteria criteria){
list.add(criteria);
}
#Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
List<Predicate> predicates = new ArrayList<>();
for (SearchCriteria criteria : list) {
if (criteria.getOperation().equals(SearchOperation.GREATER_THAN)) {
predicates.add(builder.greaterThan(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.LESS_THAN)) {
predicates.add(builder.lessThan(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.GREATER_THAN_EQUAL)) {
predicates.add(builder.greaterThanOrEqualTo(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.LESS_THAN_EQUAL)) {
predicates.add(builder.lessThanOrEqualTo(
root.get(criteria.getKey()), criteria.getValue().toString()));
} else if (criteria.getOperation().equals(SearchOperation.NOT_EQUAL)) {
predicates.add(builder.notEqual(
root.get(criteria.getKey()), criteria.getValue()));
} else if (criteria.getOperation().equals(SearchOperation.EQUAL)) {
predicates.add(builder.equal(
root.get(criteria.getKey()), criteria.getValue()));
} else if (criteria.getOperation().equals(SearchOperation.MATCH)) {
predicates.add(builder.like(
builder.lower(root.get(criteria.getKey())),
"%" + criteria.getValue().toString().toLowerCase() + "%"));
} else if (criteria.getOperation().equals(SearchOperation.MATCH_END)) {
predicates.add(builder.like(
builder.lower(root.get(criteria.getKey())),
criteria.getValue().toString().toLowerCase() + "%"));
}
}
return builder.and(predicates.toArray(new Predicate[0]));
}
My code in SearchOperation
public enum SearchOperation {
GREATER_THAN,
LESS_THAN,
GREATER_THAN_EQUAL,
LESS_THAN_EQUAL,
NOT_EQUAL,
EQUAL,
MATCH,
MATCH_END,
}
The good thing about the Criteria API is that you can use the CriteriaBuilder to build complex SQL statements based on the fields that you have. You can combine multiple criteria fields using and and or statements with ease.
How I approached something similar int he past is using a GenericDao class that takes a Filter that has builders for the most common operations (equals, qualsIgnoreCase, lessThan, greaterThan and so on). I actually have something similar in an open-source project I started: https://gitlab.com/pazvanti/logaritmical/-/blob/master/app/data/dao/GenericDao.java
https://gitlab.com/pazvanti/logaritmical/-/blob/master/app/data/filter/JPAFilter.java
Next, the implicit DAO class extends this GenericDao and when I want to do an operation (ex: find a user with the provided username) and there I create a Filter.
Now, the magic is in the filter. This is the one that creates the Predicate.
In your request, you will receive something like this: field1=something&field2=somethingElse and so on. The value can be preceded by the '<' or '>' if you want smaller or greater and you initialize your filter with the values. If you can retrieve the parameters as a Map<String, String>, even better.
Now, for each field in the request, you create a predicate using the helper methods from the JPAFilter class and return he resulted Predicate. In the example below I assume that you don't have it as a Map, but as individual fields (it is easy to adapt the code for a Map):
public class SearchFilter extends JPAFilter {
private Optional<String> field1 = Optional.empty();
private Optional<String> field2 = Optional.empty();
#Override
public Predicate getPredicate(CriteriaBuilder criteriaBuilder, Root root) {
Predicate predicateField1 = field1.map(f -> equals(criteriaBuilder, root, "field1", f)).orElse(null);
Predicate predicateField2 = field2.map(f -> equals(criteriaBuilder, root, "field2", f)).orElse(null);
return andPredicateBuilder(criteriaBuilder, predicateField1, predicateField2);
}
}
Now, I have the fields as Optional since in this case I assumed that you have them as Optional in your request mapping (Spring has this) and I know it is a bit controversial to have Optional as input params, but in this case I think it is acceptable (more on this here: https://petrepopescu.tech/2021/10/an-argument-for-using-optional-as-input-parameters/)
The way the andPredicateBuilder() is made is that it works properly even if one of the supplied predicates is null. Also, I made s simple mapping function, adjust to include for < and >.
Now, in your DAO class, just supply the appropriate filter:
public class SearchDao extends GenericDAO {
public List<MyEntity> search(Filter filter) {
return get(filter);
}
}
Some adjustments need to be made (this is just starter code), like an easier way to initialize the filter (and doing this inside the DAO) and making sure that that the filter can only by applied for the specified entity (probably using generics, JPAFIlter<T> and having SearchFilter extends JPAFilter<MyEntity>). Also, some error handling can be added.
One disadvantage is that the fields have to match the variable names in your entity class.

How can I to refactor this code and decouple method?

I have set of entities(templates)
I need to clone full this set and create same set with new Ids.
I have 3 methods like this(Entity One is User):
private Map<String, String> createUsers() {
Map<String, String> userIds = new HashMap<>();
Iterator<User> users = userService.findAllUsers();
while (users.hasNext()) {
User user = users.next();
String oldId = user.getId();
user.setId(generateNewId());
user.setName(generateNewName());
userService.saveUser(user);
userIds.put(oldId, user.getId());
}
return userIds;
}
And two similar methods(Entity two is Person and Entity Three is Book). In each method, I create new entity and store old and new IDS. After that, I clone Orders and relink old id and new id. I do it like this:
if (userIds.containsKey(order.getUserId())) {
order.setUserId(userIds.get(order.getUserId()));
}
if (personIds.containsKey(order.getPersonId())) {
order.setPersonId(personIds.get(order.getPersonId()));
}
This structure is ugly and I want to refactor it. But I have not ideas.

How to translate dynamic query from QueryDSL into JOOQ?

I use QueryDSL just for dynamic queries in Spring Boot 2+ with Spring Data JPA applications in the following manner:
#Override
public Iterable<Books> search(String bookTitle, String bookAuthor, String bookGenre) {
BooleanBuilder where = dynamicWhere(bookTitle, bookAuthor, bookGenre);
return booksRepository.findAll(where, orderByTitle());
}
public BooleanBuilder dynamicWhere(String bookTitle, String bookAuthor, String bookGenre) {
QBooks qBooks = QBooks.books;
BooleanBuilder where = new BooleanBuilder();
if (bookTitle != null) {
where.and(qBooks.title.equalsIgnoreCase(bookTitle));
}
if (bookAuthor!= null) {
where.and(qBooks.author.eq(bookAuthor));
}
if (bookGenre!= null) {
where.and(qBooks.genre.eq(bookGenre));
}
return where;
}
I want to use JOOQ in a similar transparent way, but I do not know how to do it elegantly. I also like that in JOOQ there isn't QBooks-like generated constructs, although I think JOOQ also generates some tables. Anyhow, I am confused and I couldn't find an answer online, so I am asking can it be done and how.
Thanks
jOOQ doesn't have a specific "builder" to construct your predicates. All the "building" API is located directly on the predicate type, i.e. the Condition
#Override
public Iterable<Books> search(String bookTitle, String bookAuthor, String bookGenre) {
Condition where = dynamicWhere(bookTitle, bookAuthor, bookGenre);
return dslContext.selectFrom(BOOKS)
.where(where)
.orderBy(BOOKS.TITLE)
.fetchInto(Books.class);
}
public Condition dynamicWhere(String bookTitle, String bookAuthor, String bookGenre) {
Condition where = DSL.noCondition();
if (bookTitle != null) {
where = where.and(BOOKS.TITLE.equalsIgnoreCase(bookTitle));
}
if (bookAuthor!= null) {
where = where.and(BOOKS.AUTHOR.eq(bookAuthor));
}
if (bookGenre!= null) {
where = where.and(BOOKS.GENRE.eq(bookGenre));
}
return where;
}
This is assuming:
1) That you have injected a properly configured DSLContext
2) That you're using jOOQ's code generator
For more information, see also https://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql/

Hibernate OneToMany mappedby inserts duplicate records when saved

I have a simple oneToMany relationship provided in Parent and corresponding ManyToOne in the Chile Entity class:
Parent:
#Entity
#Table(name = "FormExtraInfo")
#PrimaryKeyJoinColumn(name="form_container_id")
public class Form extends Container {
private List<Reason> reasons = new ArrayList<Reason>();
#OneToMany(mappedBy="form",cascade={javax.persistence.CascadeType.ALL},orphanRemoval=true)
#Cascade(value={CascadeType.ALL})
public List<Reason> getReasons() {
return reasons;
}
public void setReasons(List<Reason> reasons) {
this.reasons = reasons;
}
public void addReason(Reason reason) {
if (this.reasons == null) {
this.reasons = new ArrayList<Reason>();
}
this.reasons.add(reason);
}
}
Child class:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="Container_id")
public Form getForm() {
return form;
}
public void setForm(Form form) {
this.form = form;
}
Action class:
//Set the reasons
String[] reasonStatus = strutsForm.getMultiValueProperty(REASON_STATUS);
String[] reasonText = strutsForm.getMultiValueProperty(REASON_TEXT);
List<Reason> reasons = new ArrayList<Reason>();
logger.debug("form container ID : " + form.getId() +". # of Reasons for this form: "+ reasonText.length);
for (int i = 0; i < reasonText.length; i++) {
Reason r = new Reason();
r.setComment(reasonText[i]);
r.setStatusTypeCode(reasonStatus[i]);
r.setForm(form);
reasons.add(r);
}
form.setReasons(reasons);
Example case:
Status_code Reason_text
abc abc1
xyz xyz1
save the form:
Status_code Reason_text
abc abc1
xyz xyz1
abc abc1
xyz xyz1
With any operation : New insert or delete or update, it first duplicates the old data to the DB and then the operation that I performed.
Try replacing the cascade clause for this
#Cascade (value={CascadeType.SAVE_UPDATE,CascadeType.DELETE_ORPHAN})
Take a look at my blog post on mapping one-to-many http://arecordon.blogspot.com.ar/2013/05/hibernate-mapping-associations-one-to_20.html
If you can use a Set instead of a List; then, try changing the collection to a Set and make sure you overwrite equals() hashCode() as specified in here:
https://community.jboss.org/wiki/EqualsAndHashCode?_sscc=t
Also, remove the duplicated cascaded, you ca use:
#OneToMany(mappedBy="form",cascade={javax.persistence.CascadeType.ALL},orphanRemoval=true)
or
#OneToMany(mappedBy="form")
#Cascade(value={CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})

Criteria JPA 2 with 3 tables

I'm trying to create a criteria to retrieve some objects from 3 tables (Associate, Update and Detail). A Detail has reference to Associate and Update, and an Update has reference to a list of Details. My objective is to retrieve a list of Updates that has at least a Detail with null value in a specified field, given an Associate id. In JPQL was easy to do but the client said that this must be coded with criteria.
My JPQL was:
public List<Update> getUpdates(long associateId) {
TypedQuery<Update> query = em.createQuery("select distinct u from Update u, Detail dt, Associate a "
+ "where dt.update = u and dt.associate = a and a.associateId = :id and "
+ "dt.ack_date is null", Update.class);
query.setParameter("id", associateId);
return query.getResultList();
}
I tried the following, but it just returned all updates in the database:
public List<Update> getUpdates(long associateId) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Update> query = builder.createQuery(Update.class);
Root<Update> fromUpdates = query.from(Update.class);
Root<Associate> fromAssociate = query.from(Associate.class);
Root<Detail> fromDetail = query.from(Detail.class);
Join<Detail, Associate> associateJoin = fromDetail.join("associate");
Join<Detail, Update> updateJoin = fromDetail.join("update");
TypedQuery<Update> typedQuery = em.createQuery(query
.select(fromUpdates)
.where(builder.and(
builder.equal(fromAssociate.get("associateId"), associateId),
builder.equal(fromDetail.get("associate"), associateJoin),
builder.equal(fromDetail.get("update"), updateJoin),
builder.isNull(fromDetail.get("ack_date"))
))
.orderBy(builder.asc(fromUpdates.get("updateId")))
.distinct(true)
);
return typedQuery.getResultList();
}
Can anyone help me? I searched but can't find any example with 3 entities.
Each join takes you from the leftish type parameter to the rightish one. So, the details join of my code (second line) starts from fromUpdates, that is a Path<Update>, and creates something which is behind the scenes also a Path<Detail>. From that, you can build other joins. Try this (code not tested):
Root<Update> fromUpdates = query.from(Update.class);
Join<Update, Detail> details = fromUpdates.join("details");
Join<Detail, Associate> associate = details.join("associate");
List<Predicate> conditions = new ArrayList();
conditions.add(builder.equal(associate.get("associateId"), associateId));
conditions.add(builder.isNull(details.get("ack_date")));
TypedQuery<Update> typedQuery = em.createQuery(query
.select(fromUpdates)
.where(conditions.toArray(new Predicate[] {}))
.orderBy(builder.asc(fromUpdates.get("updateId")))
.distinct(true)
);
For three tables involved.
CriteriaBuilder builder = theEntityManager.getCriteriaBuilder();
CriteriaQuery query1 = builder.createQuery(BasicMemberInfo.class);
Root<Table1> table1 = query1.from(Table1.class);
Root<Table2> table2 = query1.from(Table2.class);
Root<Table3> table3 = query1.from(Table3.class);
List<Predicate> conditions = new ArrayList();
conditions.add(builder.equal(table3.get("Table1").get("memberId"), table1.get("memberId")));
conditions.add(builder.equal(table2.get("tableid").get("memberId"), table1.get("memberId")));
conditions.add(builder.equal(table2.get("indicator"), 'Y'));
conditions.add(builder.equal(table3.get("StatusCd"), "YES"));
TypedQuery<BasicCustInfo> typedQuery = theEntityManager.createQuery(
query1.multiselect(table1.get("memberId"), table2.get("AcctId"))
.where(conditions.toArray(new Predicate[] {}))
);
List<BasicMemberInfo> custList = typedQuery.getResultList();
public class BasicMemberInfo {
String memberId;
String AcctId;
public BasicCustInfo() {
// TODO Auto-generated constructor stub
}
public BasicMemberInfo( BigDecimal memberId,String AcctId ) {
this.memberId = memberId;
this.AcctId = AcctId;
}
public BigDecimal getmemberId() {
return memberId;
}
public void setmemberId(BigDecimal memberId) {
memberId = memberId;
}
public String getAcctId() {
return AcctId;
}
public void setAcctId(String AcctId) {
AcctId = AcctId;
}
}
Checkout this test with even more than three tables . Also use static meta model instead of using direct attribute names.
#Test
#Rollback(false)
#Transactional
public void
fetch() {
CriteriaBuilder cb =
entityManager.getCriteriaBuilder();
CriteriaQuery<Instructor> cq =
cb.createQuery(Instructor.class);
Root<Instructor> root =
cq.from(Instructor.class);
root.join(Instructor_.idProof);
root.join(Instructor_.vehicles);
Join<Instructor, Student> insStuJoin =
root.join(Instructor_.students);
insStuJoin.join(Student_.instructors);
Join<Student, Vehicle> stuVehcileJoin.
= insStuJoin.join(Student_.vehicles);
Join<Vehicle, Document>
vehicleDocumentJoin =
stuVehcileJoin.join(Vehicle_.documents);
DataPrinters.
listDataPrinter.accept.
(queryExecutor.fetchListForCriteriaQuery
(cq.select(root).where
(cb.greaterThan(root.get(Instructor_.id), 2),
cb.in(vehicleDocumentJoin.get
(Document_.name)).value("1")
.value("2").value("3")));
}

Categories

Resources