Hibernate Transformers.aliasToBean Josn String to List<> - spring

I have a table called user_request and it has request_payload column of type text and I want to map this column to List in my DTO class using result transformer
 private Integer id;
 private List<userRequest> userRequestList;
 // setter and getters
}
is possible to get result like this from db using result transformer

Yes that is possible. Just look into the documentation which nicely explains how you can do this ;)

Related

Spring JPA ArrayList and Lob

I'm trying to save a simple object to a JPA repository and there is something I cannot understand.
When I try to store a list of Integers like this, I get a runtime error that I cannot cast an ArrayList to a blob:
#Lob
List<Integer> bla = new ArrayList<>();
However if I do it like this:
#Lob
BogusClass bogus;
where
class BogusClass implements Serializable {
List<Integer> bla = new ArrayList<>();
}
everything works fine and dandy. But Integers are serializable by default and in the Lob documentation it says that collections should be accepted. Can someone explain the difference to me and why the first option does not work?
In the case of a relational database, it is not possible to store multiple values in a single column.
When you need to save the list of objects in DB, mainly you have 2 options:
use #ElementCollection, and #CollectionTable annotations. A new table will be created(one to many/many to one);
create a converter that will convert the data list into comma-separated value

Jooq enum converter uses the ordinal number. How can I switch to use the enum value number instead?

We have an Enum class with customized values. The values are different from their ordinals intentionally for business purpose which I cannot change.
enum class Role(val value: Int) {
EXECUTOR(1),
MONITOR(3),
ADMIN(5),
companion object {
private val map = Role.values().associateBy(Role::value)
fun fromInt(role: Int) = map[role]
}
}
We are using JOOQ and postgres. We use the JOOQ default EnumConverter to convert db role integer values to objects.
ForcedType()
.withUserType("com.company.enums.Role")
.withEnumConverter(true)
.withIncludeExpression("role"),
However we noticed a problem -- the database stored the ordinals of the enum, instead of the values. For example we see in the db in roles column, the db value is 1, and the translated Enum is MONITOR, coz MONITOR has an ordinal of 1.
How can we store the values of Enum into db using JOOQ?
Thank you!
You can of course implement a custom converter from scratch, as you suggested in your own answer. But do note that starting from jOOQ 3.16 and https://github.com/jOOQ/jOOQ/issues/12423, you can simplify that implementation by extending the org.jooq.impl.EnumConverter like this:
class RoleConverter : EnumConverter<Int, Role>(
Int::class.java,
Role::class.java,
Role::value
)
Ohhh I figured it out! There's Custom Converter https://www.jooq.org/doc/latest/manual/code-generation/custom-data-types/ which is exactly what I need.

How to pass column name dynamically inside a #Query annotation using Spring data JPA

I have entity like:
#Id
#Column_name = "abc"
int pk;
#Column_name = "def"
int id;
And I have Repository as:
interface fetchDataRepository extends jpaRepository<className, int> {
#Query("Select S_Test.nextVal from dual");
Long generateId();
}
In above example S_Test is hardcoded sequence name.
But the problem is that I want to pass sequence name dynamically as follows:
Long generateId(#Param("sequenceName") String sequenceName)
and use inside #Query annotation as:
#Query("Select :sequenceName.nextVal from dual");
Is there anyway to do that? Any suggestion would be appreciated.
Edit: Isn't there possible to use #(#entityName). If yes, then please tell me how?
Unfortunately you can only substitute in things that you could do in JDBC anyway (so, pretty much just values in the INSERT and WHERE clauses). No dynamic table, column, schema names are supported.
There is one exception that may apply, and that is a limited subset of SpEL can be used. There is one variable available - #entityName. So, assuming that the #Entity annotation on your entity class is named identically to the sequence, you could use an #Query like so:
#Query("Select #{#entityName}.nextVal from dual");
Otherwise, since your query is simple and does not involve any object relational mapping, you would probably need to Create a custom repository implementation and inject a JdbcTemplate into it in order to run the query.
Else you could inject an EntityManager and try using the JPA Criteria API - but again you arent actualy trying to map a resultset to an entity so JdbcTemplate will be simpler.

Spring data - Order by multiplication of columns

I came to a problem where I need to put ordering by multiplication of two columns of entity, for the sake of imagination entity is:
#Entity
public class Entity {
#Column(name="amount")
private BigDecimal amount;
#Column(name="unitPprice")
private BigDecimal unitPrice;
.
.
.
many more columns
}
My repo interface implements JpaRepository and QuerydslPredicateExecutor,
but I am struggling to find a way to order my data by "amount*unitPrice",
as I can't find a way to put it into
PageRequest (new Sort.Order(ASC, "amount * unitPrice"))
without having PropertyReferenceException: No property amount * unitPrice... thrown.
I can't user named query, as my query takes quite massive filter based on user inputs (can't put where clause into query, because if user hasn't selected any value, where clause can't just be in query).
To make it simple. I need something like findAll(Predicate, Pageable), but I need to force that query to order itself by "amount * unitPrice", but also have my Preditate (filter) and Pageable (offset, limit, other sortings) untouched.
Spring Sort can be used only for sorting by properties, not by expressions.
But you can create a unique sort in a Predicate, so you can add this sort-predicate to your other one before you call the findAll method.

Query by Example Spring Data

I have domain object Person with date fields:
public class Person {
#Id
private Long id;
private Date date
Build example like this:
Person person = new Person();
person.setSomeOtherFields("some fields");
Example<Person> example = Example.of(person);
How i can create example query with date range (search entity contains date greater or equal from some date and less or equal some another date)?
The Spring Data JPA query-by-example technique uses Examples and ExampleMatchers to convert entity instances into the underlying query. The current official documentation clarifies that only exact matching is available for non-string attributes. Since your requirement involves a java.util.Date field, you can only have exact matching with the query-by-example technique.
You could write your own ExampleMatcher that returns query clauses according to your needs.

Resources