How can I get a value from entity as String - spring

Is it possible to get a value from an entity with the field name as String?
For example:
public class User{
private String lastname;
private String firstname;
}
And I have the String lastname.
How can I get the lastname?
repo.findby...?
Thanks

Related

Spring MongoDB Query Criteria by keys of Map

I have document
public class Person {
private String id;
private String email;
private String firstName;
private String lastName;
private Map<String, Boolean> hobbies;
}
And have request with Set of reqHobbies. I need to find persons from my collection with hobbies of set.
I find a solution like
query.addCriteria(Criteria.where("hobbies").all(reqHobbies)); - this work, if my hobbies is List/Set.
Thanks for the help!

extract less number of columns from database table as defined in #Entity class and map to same entity pojo in spring boot

My #Entity class is
#Entity
class Demo{
#Id
private int id;
private int firstName;
private String lastName;
private String address;
}
And the #Repositiory Interface is having method as below
#Query(value="select d.id,d.firstName from demo d",nativeQuery=true)
List<Demo> fetchDetails();
Here exception is thrown as : The field "lastName" is not present in ResultSet
Do i need to create another pojo that contain id,firstName as variable and change fetchDetails() methods to as below:
#Query(value="select d.id,d.firstName from demo d",nativeQuery=true)
List<New Pojo class with only 2 fields that is to be selected> fetchDetails();
i want the partially selected resultset to get mapped to Entity Demo automatically.
I their any way to map these two columns to the Entity Demo
You can use Class-Based Projections that you can have a lot of constructor you need according to all fields you want to fetch
For example, here's a projection class for the Demo entity:
public class DemoDto {
private int id;
private int firstName;
private String lastName;
private String address;
// getters, equals and hashCode
}
public DemoDto(String firstName) {
this.firstName = firstName;
}
public DemoDto(int id, String firstName) {
this.id = id;
this.firstName = firstName;
}
public DemoDto(int id, String firstName, String address) {
this.id = id;
this.firstName = firstName;
this.address = address;
}
You must also define equals and hashCode implementations – they allow Spring Data to process projection objects in a collection.
In your repository you can add some query with JPQL Constructor like:
#Query(value="select new your.class.fullname.package.DemoDto(d.firstName) from Demo d")
List<DemoDto> fetchNameOnly();
#Query(value="select new your.class.fullname.package.DemoDto(d.id, d.firstName) from Demo d")
List<DemoDto> fetchIdAndNameOnly();
#Query(value="select new your.class.fullname.package.DemoDto(d.id, d.firstName, d.address) from Demo d")
List<DemoDto> fetchAllDetails();
Projections are introduced for that exact reason. Have a look at the documentation here
What you need is this, create an interface like this with the getter method for the fields you want in the result.
interface IdAndNameOnly {
String getFirstname();
int getId();
}
Modify the query like this. You do not need #Query for simple queries like the one you have.
List<IdAndNameOnly> findAll();
You can convert object of type IdAndNameOnly to your Entity type. But that doesn't make much sense. You can just get the fields which you need from the IdAndNameOnly object. If not what is the point of fetching fewer fields.
If I'm not mistaken you need to create a custom constructor and use it JPQL Constructor Expressions.
Something like this would do the job:
#Entity
class Demo{
#Id
private int id;
private int firstName;
private String lastName;
private String address;
public Demo() {
// JPA needs the default constructor
}
public Demo(int id, String firstName) {
this.id = id;
this.firstName = firstName;
}
}
And the usage something like this:
#Query(value="select new your.class.fullname.package.Demo(d.id,d.firstName) from Demo d")
List<Demo> fetchDetails();

Spring Data JPA Mapping Exception No Dialect mapping for JDBC type: -9

I am trying to use a projection and am getting the following error. Not sure what the issue is.
Here is the projection:
public interface UserMini {
Long getApproverKey();
String getEmailAddress();
String getFirstName();
String getLastName();
Long getUserKey();
String getUserName();
}
Here is the Query in the repository:
#RestResource(path="getUserMini")
#Query(value="SELECT approverKey, emailAddress, firstName, lastName, userKey, userName FROM [dbo].BdmUser WHERE userKey = :userKey ", nativeQuery=true)
UserMini getUserMini(#Param("userKey") long userKey);
Here is the Entity
#Table (name="[BdmUser]")
#Entity
public class BdmUser {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long userKey;
private Long priceListKey;
private String firstName;
private String lastName;
private String userName;
private String emailAddress;
private String password;
private Boolean active;
private Long approverKey;
private BigDecimal orderLimit;
private Long salesOfficeKey;
private Long reportsToId;
private Boolean requiresOrderApproval;
private Date lastLoginDate;
private String rowIsCurrent;
private Date rowStartDate;
private Date rowEndDate;
#Column(name="HashByteValueType1", updatable=false, insertable=false)
private String hashByteValueType1;
#Column(name="HashByteValueType2", updatable=false, insertable=false)
private String hashByteValueType2;
private String rowChangeReason;
#Column(name="DQScoreKey")
private Integer dqScoreKey;
private Integer insertAuditKey;
private Integer updateAuditKey;
Try to cast the NVARCHAR to VARCHAR in your query
CONVERT(varchar,theNVarcharColumn)

Spring data mongoDB: Get the distinct rows with pagination

I have User class like,
#Document(collection = "users")
public class User {
private String id;
private String firstName;
private String lastName;
private String jobTitle;
private String email;
private String phoneNumber;
}
And UserDimension as,
#Document(collection = "userDimensions")
public class UserDimension{
private String id;
private String userId;
private String dimensionId;
private String status;
}
I want the userDimension records from mongoDB based on distinct userId with pagination in spring data mongoDB ?
I am using the query like,
Query query = new Query();
List<UserDimension> userDimensionList = null;
// apply pagination parameters to the search criteria
query.with(pageable);
userDimensionList = mongoTemplate.getCollection("userDimensions").distinct("userId", query.getQueryObject());
But it still giving me the total records.

Groovy : fetching values of nested objects using xpath kind

I have POJO with nested objects which i need to translate to a simple object with out nesting
for example i have a Person and Address as below
public class Person {
private String firstName;
private String lastName;
private Address address;
}
public class Address {
private String lineOne;
private String lineTwo;
}
I need to translate Person to PersonFlat which looks like
public class PersonFlat {
private String firstName;
private String lastName;
private String Address_lineOne;
private String Address_lineTwo;
}
is there any way where i can do xpath kind of extraction on the Person instance to get the Address.lineOne and Address.lineTwo using groovy metaClass ?

Resources