Multiple types and iteraction over MyBatis parameterClass - dao

I need a query in a MyBatis dao xml file which will receive two parameters: a String object and a list of Strings. It should look something like this:
<select id="findMinTime" parameterClass="????" resultClass="java.lang.Integer">
select min(time) from table_$first_parameter$ where name in <iterate over second_parameter>
</select>
Any ideas on how to format this query and how to specify these two different parameters?

You can't pass two parameters in this way. You should create new class, for example MyParam with these two fields:
public class MyClass {
private String param1;
private List<String> param2;
// getters and setters
}
and use that class in your query. Access those fields like any other fields by name in your query.

Related

Can sql query result be manually mapped with room?

Lets say in my dao class i have a method annotated with sql: SELECT id, name, lat, long FROM table WHERE id = :id.
i want to map that to object like (pseudo):
public class Something {
public string Id;
public string Name;
public GeoLocation Location;
public Something(id, name, lat, long) {
this.Id = id;
this.Name = name;
this.Location = new GeoLocation(lat, long);
}
}
so, point is that i want to map flat select result into model with children made from some of the return fields.
Important is that i don’t want to have public get/set for all fields that sql returns.
I also want to avoid any room annotations on Something if possible (i am aware of solutions that involve #Embedded annotations).
In room the only possible way to convert fields into POJO that has no boiler point is indeed #Embedded annotation. Thats the best and simplest way to do it.
You can convert your sql query to your desired model with some other few methods which are not feasible.
Intermediate Model. That is convert your SQL result to a model that one to one matches to your fields. i.e.
public class PreSomething {
public string id;
public string name;
public long lat;
public long long;
}
After converting to PreSomething, you can have it get converted Something with any fashion you like.
Another way would be TypeConverters which changes database schema and will require you have database migration.
So, the only possible way is infact #Embedded. Now coming to your requirements,
Important is that i don’t want to have public get/set for all fields
that sql returns.
Every field that's stored in the database needs to be either public or have a "getter" method. Since your fields are all public you don't have to have any get/set for the fields.
I also want to avoid any room annotations on Something if possible (i
am aware of solutions that involve #Embedded annotations).
You have to annotate #Embedded the GeoLocation object (not Something) in order to be able to map your fields to a POJO.
One other thing to note that you SQLite, in that fashion Room, is case sensitive so. If you have to specify your fields with lowercase if your columns are lowercase. Otherwise you have to annotate them with #ColumnInfo and correct column name.

How can I map the fields return in JSON with my entity provided the key in JSON has different name than fields in my entity

I am trying to Map a JSON response to a Java POJO which has a different field name from different API.
I need an efficient way to do this reducing boilerplate codes.
I have tried mapping the JSON property field in Java POJO.
However, the problem is I am fetching data from different sources.
Let's say I have below user class
Class User{
String name;
String contact;
}
The JSON I may receive from different sources can be
{"name": "ABC" , "contact": "123456"}
or
{"userName": "XYZ" , "mobileNo":"4354665"}
There may be more variations as we go on integrating more API's
Is there a way I can archive this?
above is just a simple example
there could be more complex JSON object I may need to read.
like List of User etc.
You can use the #JsonAlias() to give the variable more than one JSON key binding.
#JsonAlias is introduced in Jackson 2.9 release. #JsonAlias defines one or more alternative names for a property to be accepted during deserialization i.e. setting JSON data to Java object. But at the time of serialization i.e. while getting JSON from Java object, only actual logical property name is used and not alias. #JsonAlias is defined as follows.
#Entity
Class User{
#JsonProperty()
#JsonAlias({"name", "userName"})
String name;
#JsonProperty()
#JsonAlias({"contact", "mobileNo"})
String contact;
}
You could use the #JsonSetter annotation like :
public class User{
public String contact;
public String name;
#JsonSetter("name")
public void setName(String name) {
this.name = name;
}
#JsonSetter("userName")
public void setName(String name) {
this.name = name;
}
}
Instead of directly mapping to an entity class , you should have a DTO object or model in between to map the json response. Then, you can convert that into any entity you may choose.If you are fetching the data from different sources , it means you are calling different endpoints, why don't you create different DTO 's for that.In that way even if one of the endpoints introduce a change , it won't affect the rest of the endpoint calls.
Vice-versa you could have different DTO objects being returned from the two endpoints instead of returning the same Entity class as well, that way you can have control over which attributes should be there in the response.
To reduce the boiler plate code, you could use library such as MAP STRUCT to enable conversion between entity and DTO objects easily
Read here about the advantages of using a DTO .

Spring- How to remove a property from a list of Objects?

I have an Entity "Person" which has following properties,
Id
Name
F-Name
Age
Address
When I call a repository function findAll() on Person, it returns a list of Persons.
List<Person> list = somefuntionToConvertIterableToList(personRepository.findAll());
this list has multiple objects of Person Type.
Person ...... Id1,Name1, F-Name1, Age1, Address1
Person .......IdN,NameN, F-NameN, AgeN, AddressN
I need to remove "Id" from all Persons, what should I do?
I know we can use "remove" to delete an element of list, but how to delete a property with in an element?
I think you need used : #JsonIgnore in Id look like:
#JsonIgnore
Field you want remove in reponse.
Or you can create DTO and put all field you want return look like :
public class PersonDTO {
//all field you want return
}
You can of course set id null or add ignores in serialization but maybe you do not want to load id at all. Usually you then would use DTO or Tuple to decide what fields to populate. So not first to populate all and then remove unneeded (I have not used your Person but just one simplified example class).
Tuple query in your repository would simply be like (JPQL):
#Query("SELECT te.name AS name, te.created as created FROM TestEntity te")
List<Tuple> findAllTuple();
This would need then do extra work to have tuple to correspond original entity when serialized. So preferably with a DTO, like:
// This class would be exactly as your Person but without that id
#AllArgsConstructor // you need the constructor for new in jpql
public class TestEntityDto {
private String name;
private LocalDateTime created;
}
while the query in your repository would be like:
#Query("SELECT NEW org.example.data.entity.dto.TestEntityDto(te.name, te.created) FROM TestEntity te")
List<TestEntityDto> findAllDto();

How to Define Dynamic Model in Spring Framework

I am using Spring Framework as my back end
I have define know as Entity class The Entity class know contain 5 Fields
Below is the class , The code below dose not have setter getter part to make shorter and cleaner
#Entity
#Table(name="TblKnow")
public class Know {
#Id
private Double idKnow;
private String SubjectKnow;
private String BodyKnow;
private String ImgKnow;
private double CountView;
In JpaRepository interface i want to only query two column not all of columns.
public interface KnowRepository extends JpaRepository<Know,Double> {
#Query("SELECT idKnow,SubjectKnow FROM Know")
public Page<Know> findCByOrderByIdKnowDesc(Pageable pageable);
Problem: i try to run but i get below exception
java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [java.lang.Long]
But if i use without below query it is fine
public Page<Know> findAllByOrderByIdKnowDesc(Pageable pageable);
You can create a custom constructor and use that to select only some fields in JPA query.
public Know(Double idKnow, String SubjectKnow) {
this.idKnow = idKnow;
this.SubjectKnow = SubjectKnow;
}
And the use this constructor in JPA query. Make sure you use complete path of class with package.
#Query("SELECT NEW packagePath.Know(idKnow,SubjectKnow) FROM Know")
query :
public Page<Know> findAllByOrderByIdKnowDesc(Pageable pageable);
works dut to you select Know objects with fields that are mapped correct into Know class (and after wrapped into Page).
with query :
#Query("SELECT idKnow,SubjectKnow FROM Know")
public Page<Know> findCByOrderByIdKnowDesc(Pageable pageable);
returns some custome bean/object that spring data can't map in correct way into Know class (as you declared it as expected return class wrapped into Page). add counstructor into Know with idKnow,SubjectKnow fields , or you can wrap it into some DTO with idKnow,SubjectKnow fields.

Spring data JPA for returning specific fields

Does Spring Data have a mechanism for returning specific fields?
I'm familiar with the syntax:
Invoice findByCode(String code);
How about this:
Integer findIdByCode(String code);
which returns the id field only. Or
Tuple findIdAndNameByCode(String code);
which returns a tuple. Or
Invoice findIdAndNameByCode(String code);
which returns an entity only populated with specific fields. Can use a constructor taking only those field if defined - else construct empty and populate the fields.
EDIT
To qualify some more, I'm aware of solutions like #Query, constructor expressions and now, #NamedEntityGraph. My question is simply - does Spring data support such a shorthand syntax as I'm suggesting?
If not, perhaps this is a cool enhancement for a later version...
I'm not looking for workarounds.
You can use JPQL Constructor Expressions:
SELECT NEW com.company.PublisherInfo(pub.id, pub.revenue, mag.price)
FROM Publisher pub JOIN pub.magazines mag WHERE mag.price > 5.00
The constructor name must be fully qualified
If you want to return just 1 field from table and it's primitive(or autoboxing), you can use next:
#Query("select distinct t.locationId from Table t")
List<Long> findAllWashroomLocationId();
Where:
Table - name of class which represent your table
t - alias
locationId - name of field(in your Table object)
Long - type of locationId (Integer, String, ...)
Not sure if what you're trying to achieve is the same as using multiple projections on the same JPA generated query (where method name are the same). I have posted an answer in this post.
https://stackoverflow.com/a/43373337/4540216
So I've managed to figure out how to use multiple projections with a
single query.
<T> T getByUsername(String username, Class<T> projection) This allows the method caller to specified the type of projection to be
applied to the query.
To further improve this so it is less prone to error, I made a blank
interface that the projection will have to extend in order to be able
to insert class into the parameter.
public interface JPAProjection {
}
public interface UserRepository extends CrudRepository<UserAccount, Long> {
<T extends JPAProjection > T getByUsername(String username, Class<? extends JPAProjection> projection);
}
Projection Interface
public interface UserDetailsProjection extends JPAProjection{
#Value("#{target.username}")
String getUsername();
#Value("#{target.firstname}")
String getFirstname();
#Value("#{target.lastname}")
String getLastname();
}
Then I can call the query method by
getByUsername("...", UserDetailsProjection.class)
i have a nativequery,
this is a insert and i going to return all fields after insert whit "RETURNING *"
this query return all fields of my database, and this data going to save in my entity
"Perfil Detalles"
my entity have all configurations of my fields of my database
#Query(
value= "INSERT INTO \"USUARIO\".\"PERFIL_CONFIGURACION\" (id_perfil, id_group, id_role) VALUES(:id_perfil, :id_group, :id_role) returning *",
nativeQuery = true)
public PerfilDetalles insertPerfilDetalles(
#Param("id_perfil") Long id_perfil,
#Param("id_group") int id_group,
#Param("id_role") int id_role);

Resources