Result row : null from HibernateTemplate Find() - spring

The following line is returning nulls:
List accountList = hibernateTemplate.find("from Accounts a where a.userId=?",userId);
I am getting following information in the Console:
2013-04-03 21:09:48 DEBUG Loader:1197 - result row: null
2013-04-03 21:09:48 DEBUG Loader:1197 - result row: null
Here is my Entity class:
#Repository
#Entity
#Table(name = "ACCOUNTS")
public class Accounts {
#Column(name="ACCOUNT_ID")
#Id
#GeneratedValue
private int accountId;
#Column(name="ACCOUNT_NUMBER")
private String accountNumber;
#Column(name="ACCOUNT_TYPE_CODE")
private String accountTypeCode;
#Column(name="USER_ID")
private String userId;
#Column(name="ACCOUNT_NAME")
private String accountName;
#Column(name="DATE_OPENED")
private Date dateOpened;
#Column(name="DATE_CLOSED")
private Date dateClosed;
#Column(name="CURRENT_BALANCE")
private double currentBalance;
#Column(name="OTHER_ACCOUNT_DETAILS")
private String otherAccountDetails;
#Column(name="ADD_TS")
private Date addTimestamp;
#Column(name="ADD_USR")
private String addUser;
#Column(name="UPDT_TS")
private Date updateTimestamp;
#Column(name="UPDT_USR")
private String updateUser;
#ManyToOne
private Customer customer;
Can anyone please help me with this? I would really appreciate it.
Here is the query that Hibernate generated
Hibernate: select accounts0_.ACCOUNT_ID as ACCOUNT1_23_, accounts0_.ACCOUNT_NAME as ACCOUNT2_23_, accounts0_.ACCOUNT_NUMBER as ACCOUNT3_23_, accounts0_.ACCOUNT_TYPE_CODE as ACCOUNT4_23_, accounts0_.ADD_TS as ADD5_23_, accounts0_.ADD_USR as ADD6_23_, accounts0_.CURRENT_BALANCE as CURRENT7_23_, accounts0_.customer_CUSTOMER_ID as customer14_23_, accounts0_.DATE_CLOSED as DATE8_23_, accounts0_.DATE_OPENED as DATE9_23_, accounts0_.OTHER_ACCOUNT_DETAILS as OTHER10_23_, accounts0_.UPDT_TS as UPDT11_23_, accounts0_.UPDT_USR as UPDT12_23_, accounts0_.USER_ID as USER13_23_ from ACCOUNTS accounts0_ where accounts0_.USER_ID=?
is there something wrong in query? or domain configuration?
Please help me.

I'm a little don't understand that why set the column of USER_ID String(varchar) type, but about your situation, you can write like this:
hibernateTemplate.find("from Accounts a where a.userId='" + userId + "'");
it'll work well, maybe help you:)

Related

Spring Boot + Webflux + Reactive MongoDB - get document by property Id

I'd like to find all Offer documents by Offer.ProductProperties.brand:
#Document(collection = "offers")
public class Offer {
#Id
private String id;
#NotNull
#DBRef
private ProductProperties properties;
ProductProperties:
#Document(collection = "product_properties")
public class ProductProperties {
#Id
private String id;
#NotNull
#NotEmpty
private String brand;
Service:
Flux<ProductProperties> all = productPropertiesRepository.findAllByBrand(brand);
List<String> productPropIds = all.toStream()
.map(ProductProperties::getId)
.collect(Collectors.toList());
Flux<Offer> byProperties = offerRepository.findAllByProperties_Id(productPropIds);
But unfortunately byProperties is empty. Why?
My repository:
public interface OfferRepository extends ReactiveMongoRepository<Offer, String> {
Flux<Offer> findAllByProperties_Id(List<String> productPropertiesIds);
}
How to find all Offers by ProductProperties.brand?
Thanks!
After reading some documentation found out that You cannot query with #DBRef. Hence the message
Invalid path reference properties.brand! Associations can only be
pointed to directly or via their id property
If you remove DBRef from the field, you should be able to query by findAllByProperties_BrandAndProperties_Capacity.
So the only ways is how you are doing. i.e. Fetch id's and query by id.
As I said in the comment, the reason it is not working is because return type of findAllByProperties_Id is a Flux. So unless u execute a terminal operation, you wont have any result. Try
byProperties.collectList().block()

Bulk data to find exists or not : Spring Data JPA

I get an Post request that would give me a List<PersonApi> Objects
class PersonApi {
private String name;
private String age;
private String pincode ;
}
And I have an Entity Object named Person
#Entity
#Table(name = "person_master")
public class Person{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
#Column(name = "name")
String name;
#Column(name = "age")
String age;
#Column(name = "pincode ")
String pincode ;
}
My record from Post request would look something like this (pseudocode representation of the data below)
[
"Arun","33","09876gh"
"James","34","8765468"
]
I need to do a bulk-validation using Spring JPA.. Give the List<PersonApi> and get a True or False based on the condition that all the entries in the PersonApi objects list should be there in the database.
How to do this ?
The selected answer is not a right one. (not always right)
You are selecting the whole database to check for existence. Unless your use case is very special, i.e. table is very small, this will kill the performance.
The proper way may start from issuing repository.existsById(id) for each Person, if you never delete the persons, you can even apply some caching on top of it.
exists
Pseudo Code:
List<PersonApi> personsApiList = ...; //from request
List<Person> result = personRepository.findAll();
in your service class you can access your repository to fetch all database entities and check if your list of personapi's is completeley available.
boolean allEntriesExist = result.stream().allMatch(person -> personsApiList.contains(createPersonApiFromPerson(person)));
public PersonApi createPersonApiFromPerson(Person person){
return new PersonApi(person.getName(), person.getAge(), person.getPincode());
}

Spring Data query over two documents

I have an m:n connection in my MongoDB, MessageUserConnection is the class between User and Message.
Now I will get all MessageUserConnections where MessageUserConnection#confirmationNeeded is true, read is false and Message#receiveDate is not older than the last week.
Is there any possibility to do this with Spring Data?
Thanks a lot!
public class MessageUserConnection {
#Id
private String id;
#DBRef
private User userCreatedMessage;
#DBRef
private Message message;
private Boolean confirmationNeeded;
private Boolean read;
}
public class Message {
#Id
private String id;
private String title;
private String message;
private DateTime receiveDate;
}
[EDIT]
I have tried it by my own:
#Query("FROM MessageUserConnection AS muc WHERE muc.confirmationNeeded = ?0 AND muc.message.receiveDate = ?1")
List<MessageUserConnection> findMessageUserConnectionByConfirmationNeededAndReceiveDate(final Boolean confirmationNeeded, final DateTime receiveDate);
and I get the following exception:
Caused by: com.mongodb.util.JSONParseException:
FROM MessageUserConnection AS muc WHERE muc.confirmationNeeded = "_param_0" AND muc.message.receiveDate = "_param_1"
Does anyone know what I am doing wrong here?
Thanks a lot!
[EDIT]
I run into another problem. My query currently looks like this.
#Query("{$and : [{'confirmationNeeded' : ?0}, {'message.receiveDate' : ?1}]}")
where confirmationNeeded is a boolean and message.receiveDate is Joda#DateTime. With this query I get the following exception:
org.springframework.data.mapping.model.MappingException: Invalid path reference message.receiveDate! Associations can only be pointed to directly or via their id property!
Does that mean that I only can join to message.id?
Thanks a lot!

Variable 'this.userInfo' is unbound and cannot be determined

I am developing a maven JDO project, but I am getting this error when I am trying to make relation between two tables (user_login, user_role)
User_Login: user_id(primary key), user_name, user_password,user_role_id
User_Role: id(primary key), role
user_role_id is same as id of user_role table
User.java:
#PersistenceCapable(table = "user_login")
public class User {
#PrimaryKey
#Column(name="user_id")
private Integer userId=0;
#Column(name="user_profile_name")
private String userProfileName=null;
#Column(name="user_email")
private String userEmail=null;
#Column(name="user_contact")
private String userContact=null;
#Column(name="user_name")
private String userName=null;
#Column(name="user_password")
private String userPassword=null;
#ManyToOne
#Column(name="user_role_id")
private Integer userRoleId=0;
Role.java:
#PersistenceCapable(table = "user_role")
public class Role {
#PrimaryKey
#Column(name="id")
private Integer id=0;
#Column(name="role")
private String role=null;
#OneToMany
private User userInfo=null;
DAOImpol:
public List<Role> getUser(String username, String userpassword) {
PersistenceManager pm = this.pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
JDOPersistenceManager jdopm = (JDOPersistenceManager)pm;
try {
// Start the transaction
tx.begin();
TypesafeQuery<User> tq = jdopm.newTypesafeQuery(User.class);
//QUser user = QUser.candidate();
QRole role = QRole.candidate();
QUser userInfo=role.userInfo;
List<Role> result = tq.filter(userInfo.userName.eq(username).and(userInfo.userPassword.eq(userpassword))).executeList();
//result = tq.executeResultList(true, user.userId);
if(result.size()>0){
log.info(">>>>>00000000"+" "+result.get(0).getUser().getUserEmail());
log.info(">>>>>11111111"+" "+result.get(0).getRoleId()+" "+result.get(0).getRole());
}else{
log.info("<<<<<<<=====000000");
}
// Commit the transaction, flushing the object to the datastore
tx.commit();
return result;
}
finally {
if (tx.isActive())
{
// Error occurred so rollback the transaction
tx.rollback();
}
pm.close();
}
I am getting this error:
javax.jdo.JDOUserException: Variable 'this.userInfo' is unbound and
cannot be determined (is it a misspelled field name? or is not intended
to be a variable?)
NestedThrowables:
org.datanucleus.exceptions.NucleusUserException: Variable
'this.userInfo' is unbound and cannot be determined (is it a
misspelled
field name? or is not intended to be a variable?)
I found that you'll get this error from JDO if you're using progaurd and progaurd renames your private fields. Adding a -keep to the progaurd config to keep the package with your Persistence Capable classes will fix it.
For example, if you keep all of your Persistence Capable classes in com.example.server.orm package you'd add this to progaurd.conf
-keep class com.example.server.orm.** {*;}

Hibernate tuple criteria queries

I am trying to create a query using hibernate following the example given in section 9.2 of chapter 9
The difference with my attempt is I am using spring MVC 3.0. Here is my Address class along with the method i created.
#RooJavaBean
#RooToString
#RooEntity
#RooJson
public class Address {
#NotNull
#Size(min = 1)
private String street1;
#Size(max = 100)
private String street2;
private String postalcode;
private String zipcode;
#NotNull
#ManyToOne
private City city;
#NotNull
#ManyToOne
private Country country;
#ManyToOne
private AddressType addressType;
#Transient
public static List<Tuple> jqgridAddresses(Long pID){
CriteriaBuilder builder = Address.entityManager().getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<Address> addressRoot = criteria.from( Address.class );
criteria.multiselect(addressRoot.get("id"), addressRoot.get("street1"), addressRoot.get("street2"));
criteria.where(builder.equal(addressRoot.<Set<Long>>get("id"), pID));
return Address.entityManager().createQuery( criteria ).getResultList();
}
}
The method called jqgridAddresses above is the focus. I opted not to use the "Path" because when I say something like Path idPath = addressRoot.get( Address_.id ); as in section 9.2 of the documentation, the PathAddress_.id stuff produces a compilation error.
The method above returns an empty list of type Tuple as its size is zero even when it should contain something. This suggests that the query failed. Can someone please advise me.
OK so i made some minor adjustments to my logic which is specific to my project, however, the following approach worked perfectly. Hope it hepls someone in need !
#Transient
public static List<Tuple> jqgridPersons(Boolean isStudent, String column, String orderType, int limitStart, int limitAmount){
CriteriaBuilder builder = Person.entityManager().getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<Person> personRoot = criteria.from(Person.class );
criteria.select(builder.tuple(personRoot.get("id"), personRoot.get("firstName"), personRoot.get("lastName"), personRoot.get("dateOfBirth"), personRoot.get("gender"), personRoot.get("maritalStatus")));
criteria.where(builder.equal( personRoot.get("isStudent"), true));
if(orderType.equals("desc")){
criteria.orderBy(builder.desc(personRoot.get(column)));
}else{
criteria.orderBy(builder.asc(personRoot.get(column)));
}
return Address.entityManager().createQuery( criteria ).setFirstResult(limitStart).setMaxResults(limitAmount).getResultList();
}

Resources