Android room compiler error when trying to return a list of own objects in the DAO: incompatible types: <null> cannot be converted to int - sql

I am using room for database operations. I have a class TableQuestion which holds a string and a id and I have a class TableAnswer which holds a string, an id plus the id of the question where it is refering to. QuizTask brings together the Question with all its answers. The query getQuestionsWithAnswer should return a QuizTask which wraps the question with all its answers. The error metioned in the title happens in auto-generated code of room.
The relevant part of the interface:
#android.arch.persistence.room.Dao
public interface dbDao {
#Transaction
#Query("SELECT table_question.question, table_answer.answer FROM table_question, table_answer WHERE table_question.id = table_answer.id_question")
LiveData<List<QuizTask>> getQuestionsWithAnswers();
}
Class TableQuestion:
#Entity(foreignKeys = #ForeignKey(entity = TableQuestionnaire.class,
parentColumns = "id",
childColumns = "id_questionnaire",
onDelete = CASCADE),
tableName = "table_question")
public class TableQuestion {
#PrimaryKey
public final int id;
#NonNull
public String question;
#NonNull
public int id_questionnaire;
public String subject;
public String category;
public String sub_category;
#Ignore
public String questionnaire;
public TableQuestion(int id, #NonNull String question, int id_questionnaire, String subject, String category, String sub_category) {
this.id = id;
this.question = question;
this.id_questionnaire = id_questionnaire;
this.questionnaire = null;
this.subject = subject;
this.category = category;
this.sub_category = sub_category;
}
public void setQuestionnaire(String questionnaire){
this.questionnaire = questionnaire;
}
}
Class TableAnswer:
#Entity(foreignKeys = #ForeignKey(entity = TableQuestion.class,
parentColumns = "id",
childColumns = "id_question",
onDelete = CASCADE),
tableName = "table_answer")
public class TableAnswer {
#PrimaryKey
public final int id;
#NonNull
public String answer;
#NonNull
public final int id_question;
public boolean rightAnswer;
public TableAnswer(int id, String answer, int id_question, boolean rightAnswer) {
this.id = id;
this.answer = answer;
this.id_question = id_question;
this.rightAnswer = rightAnswer;
}
}
Class QuizTask:
public class QuizTask {
#Embedded
private TableQuestion question;
#Relation(parentColumn = "id", entityColumn = "id_question")
private List<TableAnswer> answers;
public void setQuestion(TableQuestion question){ this.question = question; }
public TableQuestion getQuestion(){
return question;
}
public void setAnswers(List<TableAnswer> answers) { this.answers = answers; }
public List<TableAnswer> getAnswers() {
return answers;
}
}
AndroidStudio doesn't show any error upon compilation. When room auto-generates the code for getQuestionWithAnswers it shows a compiler error "incompatible types: cannot be converted to int". In the auto-generated dbDao_Impl.java is a row where a TableQuestion object is tried to create but with null for the id parameter. That's where the error occurs. What do I have to change?

I found the issue:
#Query("SELECT table_question.question, table_answer.answer FROM table_question, table_answer WHERE table_question.id = table_answer.id_question")
There is no id selected but used later on. That's why room tries to create objects with Id = null which is not possible. So simply change to:
#Query("SELECT * FROM table_question, table_answer WHERE table_question.id = table_answer.id_question")

Related

Hibernate QueryException Named parameter not bound error

I keep getting the error org.hibernate.QueryException: Named parameter not bound : item when I start my transaction in JPA using EntityManager createNativeQuery. I have my code below utilizing the entity manager, along with my embeddedID class (for the composite key) and my persistence entity bean. Is there a problem in my query syntax? I am not sure as I've tried multiple ways of formatting the sql (coming from a properties file where there resides multiple sqls used throughout the project, and attempting to persist data to an oracle db). I am not sure why I keep falling on this error. I want to persist this data to my oracle database but this error keeps preventing that.
Query from query.properties file:
insertPromoData =INSERT INTO TEST.U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY, U_TIMESTAMP) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity, SYSDATE)
Embeddedable Class for establishing composite primary key on the target table:
#Embeddable
public class PromoID implements Serializable {
#Column(name = "ITEM")
private String item;
#Column(name = "LOC")
private String loc;
#Column(name = "WK_START")
private Date weekStart;
#Column(name = "TYPE")
private int type;
#Column(name = "FCSTID")
private String forecastId;
#Column(name = "U_TIMESTAMP")
private Timestamp insertTS;
public PromoID() {
}
public PromoID (String item, String loc, Date weekStart, int type, String forecastId, Timestamp insertTS) {
this.item = item;
this.loc = loc;
this.weekStart = weekStart;
this.type = type;
this.forecastId = forecastId;
this.insertTS = insertTS;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Date getWeekStart() {
return weekStart;
}
public void setWeekStart(Date weekStart) {
this.weekStart = weekStart;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getForecastId() {
return forecastId;
}
public void setForecastId(String forecastId) {
this.forecastId = forecastId;
}
public Timestamp getInsertTS() {
return insertTS;
}
public void setInsertTS(Timestamp insertTS) {
this.insertTS = insertTS;
}
//removed hashcode and equals methods for simplicity
Persistence Entity Bean:
#Entity
#Table(name = "U_USER_PROMO")
public class InsertPromoData {
#EmbeddedId
private PromoID id;
/*#Column(name="BATCH_ID")
String batchID;*/
#Column(name="ITEM")
String item;
#Column(name="LOC")
String loc;
#Column(name="WK_START")
String weekStart;
#Column(name="TYPE")
String type;
#Column(name="FCSTID")
String forecastId;
#Column(name="U_TIMESTAMP")
String insertTS;
#Column(name="NUMBER_OF_WEEKS")
String numberOfWeeks;
#Column(name="QTY")
String qty;
#Id
#AttributeOverrides(
{
#AttributeOverride(name = "item",column = #Column(name="ITEM")),
#AttributeOverride(name = "loc", column = #Column(name="LOC")),
#AttributeOverride(name = "weekStart", column = #Column(name="WK_START")),
#AttributeOverride(name = "type", column = #Column(name="TYPE")),
#AttributeOverride(name = "forecastId", column = #Column(name="FCSTID"))
}
)
public PromoID getId() {
return id;
}
public void setId(PromoID id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public String getWeekStart() {
return weekStart;
}
public void setWeekStart(String weekStart) {
this.weekStart = weekStart;
}
public String getNumberOfWeeks() {
return numberOfWeeks;
}
public void setNumberOfWeeks(String numberOfWeeks) {
this.numberOfWeeks = numberOfWeeks;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getForecastId() {
return forecastId;
}
public void setForecastId(String forecastId) {
this.forecastId = forecastId;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getInsertTS() {
return insertTS;
}
public void setInsertTS(String insertTS) {
this.insertTS = insertTS;
}
}
My dao OracleImpl.java using EntityManager for persisting:
public void insertPromoData(List<InsertPromoData> insertData) {
logger.debug("Execution of method insertPromoData in Dao started");
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
System.out.println("Beginning transaction for insertPromoData");
Query query = em.createNativeQuery(env.getProperty("insertPromoData"));
for (InsertPromoData promoData : insertData) {
query.setParameter("item", promoData.getItem());
query.setParameter("location", promoData.getLoc());
query.setParameter("wkStart", promoData.getWeekStart());
query.setParameter("numberOfWeeks", promoData.getNumberOfWeeks());
query.setParameter("type", promoData.getType());
query.setParameter("fcstId", promoData.getForecastId());
query.setParameter("quantity", Double.valueOf(promoData.getQty()));
}
query.executeUpdate();
System.out.println("Data for promo persisted");
em.getTransaction().commit();
}
catch(Exception e) {
logger.error("Exception in beginning transaction");
e.printStackTrace();
}
finally {
em.clear();
em.close();
}
logger.debug("Execution of method insertPromoData in Dao ended");
}
PromoValidator.java class:
List <InsertPromoData> insertPromos = new ArrayList<>();
promo.forEach(record -> {
if (record.getErrorList().size() == 0) {
rowsSuccessful++;
record.setItem(record.getItem());
record.setLoc(record.getLoc());
record.setNumber_Of_Weeks(record.getNumber_Of_Weeks());
record.setForecast_ID(record.getForecast_ID());
record.setType(record.getType());
record.setUnits(record.getUnits());
record.setWeek_Start_Date(record.getWeek_Start_Date());
insertPromos = (List<InsertPromoData>) new InsertPromoData();
for (InsertPromoData insertPromoData : insertPromos) {
insertPromoData.setItem(record.getItem());
insertPromoData.setLoc(record.getLoc());
insertPromoData.setWeekStart(LocalDate.parse(record.getWeek_Start_Date()));
insertPromoData.setNumberOfWeeks(Integer.parseInt(record.getNumber_Of_Weeks()));
insertPromoData.setType(Integer.parseInt(record.getType()));
insertPromoData.setForecastId(record.getForecast_ID());
insertPromoData.setQty(Double.parseDouble(record.getUnits()));
}
} else {
if (rowsFailure == 0) {
Util.writeHeaderToFile(templateCd, errorFile);
}
rowsFailure++;
Util.writeErrorToFile(templateCd, errorFile, record, record.getErrorList());
}
});
errorFile.close();
successFile.close();
OracleImpl.insertPromoData(insertPromos);
One of the reason this can happen is when insertData List you are passing is empty.
If I use below code ( please note that I have removed few columns to simplify it on my test environment with H2 database) - I get the error you described if empty list is passed and that's because there is indeed nothing to bind for the name parameter as the loop is not executed.
try {
em.getTransaction().begin();
System.out.println("Beginning transaction for insertPromoData");
Query query = em.createNativeQuery(
"INSERT INTO U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity)");
for (InsertPromoData promoData : insertData) {
query.setParameter("item", promoData.getId().getItem());
query.setParameter("location", promoData.getId().getLoc());
query.setParameter("wkStart", promoData.getId().getWeekStart());
query.setParameter("numberOfWeeks", promoData.getNumberOfWeeks());
query.setParameter("type", promoData.getId().getType());
query.setParameter("fcstId", promoData.getId().getForecastId());
query.setParameter("quantity", Double.valueOf(promoData.getQty()));
}
query.executeUpdate();
System.out.println("Data for promo persisted");
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
em.clear();
em.close();
}
The error I get is
org.hibernate.QueryException: Named parameter not bound : item
at org.hibernate.query.internal.QueryParameterBindingsImpl.verifyParametersBound(QueryParameterBindingsImpl.java:210)
at org.hibernate.query.internal.AbstractProducedQuery.beforeQuery(AbstractProducedQuery.java:1425)
at org.hibernate.query.internal.NativeQueryImpl.beforeQuery(NativeQueryImpl.java:249)
at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1610)
at com.danielme.blog.nativesql.dao.UserDao.insertPromoData(UserDao.java:99)
However - if I pass non-empty list - this works as expected
SQLCustomQuery:72 - Starting processing of sql query [INSERT INTO U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity)]
AbstractFlushingEventListener:74 - Flushing session
I also encountered same problem. I noticed that I was defining the parameter in the query but I was not setting its value in:
query.setParameter(parameterToBeSet,parameterValue)
For example,
String hql = "FROM COLLEGE FETCH ALL PROPERTIES WHERE studentId = :studentId AND departmentId = :departmentId AND studentName = :studentName";
DBConnectionManager.getInstance().invokeCallableOnSessionMasterDB(session -> {
Query<CollegeEntity> query = session.createQuery(hql);
query.setParameter("studentId", studentId);
query.setParameter("departmentId", departmentId);
values.addAll(query.list());
});
As you can see the student name value was not set. So, after adding:
query.setParameter("studentName", studentName);
It got solved.
GETRequest : localhost:8080/getbyCity/chennai,mumbai,kolkata -
error ---> when I send this request I got------->"Hibernate QueryException Named parameter not bound error".
Answer: when we send list of parameter we should mention the "/" at the End. ((( localhost:8080/getbyCity/chennai,mumbai,kolkata/ ))). Set the bound using "/".
In my case I have put same parameter name to the procedure as:
#Param("managementAccess") Boolean managementAccess,
#Param("managementAccess") String dealerCode,
#Param("managementAccess") String dealerName,
Here the parameter name is different but inside string the name is same.
Solution is:
#Param("managementAccess") Boolean managementAccess,
#Param("dealerCode") String dealerCode,
#Param("dealerName") String dealerName,

JPA query to retrieve data using list of matching tuples as arguments [duplicate]

I have an Entity Class like this:
#Entity
#Table(name = "CUSTOMER")
class Customer{
#Id
#Column(name = "Id")
Long id;
#Column(name = "EMAIL_ID")
String emailId;
#Column(name = "MOBILE")
String mobile;
}
How to write findBy method for the below query using crudrepository spring data jpa?
select * from customer where (email, mobile) IN (("a#b.c","8971"), ("e#f.g", "8888"))
I'm expecting something like
List<Customer> findByEmailMobileIn(List<Tuple> tuples);
I want to get the list of customers from given pairs
I think this can be done with org.springframework.data.jpa.domain.Specification. You can pass a list of your tuples and proceed them this way (don't care that Tuple is not an entity, but you need to define this class):
public class CustomerSpecification implements Specification<Customer> {
// names of the fields in your Customer entity
private static final String CONST_EMAIL_ID = "emailId";
private static final String CONST_MOBILE = "mobile";
private List<MyTuple> tuples;
public ClaimSpecification(List<MyTuple> tuples) {
this.tuples = tuples;
}
#Override
public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
// will be connected with logical OR
List<Predicate> predicates = new ArrayList<>();
tuples.forEach(tuple -> {
List<Predicate> innerPredicates = new ArrayList<>();
if (tuple.getEmail() != null) {
innerPredicates.add(cb.equal(root
.<String>get(CONST_EMAIL_ID), tuple.getEmail()));
}
if (tuple.getMobile() != null) {
innerPredicates.add(cb.equal(root
.<String>get(CONST_MOBILE), tuple.getMobile()));
}
// these predicates match a tuple, hence joined with AND
predicates.add(andTogether(innerPredicates, cb));
});
return orTogether(predicates, cb);
}
private Predicate orTogether(List<Predicate> predicates, CriteriaBuilder cb) {
return cb.or(predicates.toArray(new Predicate[0]));
}
private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
return cb.and(predicates.toArray(new Predicate[0]));
}
}
Your repo is supposed to extend interface JpaSpecificationExecutor<Customer>.
Then construct a specification with a list of tuples and pass it to the method customerRepo.findAll(Specification<Customer>) - it returns a list of customers.
It is maybe cleaner using a projection :
#Entity
#Table(name = "CUSTOMER")
class CustomerQueryData {
#Id
#Column(name = "Id")
Long id;
#OneToOne
#JoinColumns(#JoinColumn(name = "emailId"), #JoinColumn(name = "mobile"))
Contact contact;
}
The Contact Entity :
#Entity
#Table(name = "CUSTOMER")
class Contact{
#Column(name = "EMAIL_ID")
String emailId;
#Column(name = "MOBILE")
String mobile;
}
After specifying the entities, the repo :
CustomerJpaProjection extends Repository<CustomerQueryData, Long>, QueryDslPredicateExecutor<CustomerQueryData> {
#Override
List<CustomerQueryData> findAll(Predicate predicate);
}
And the repo call :
ArrayList<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("a#b.c","8971"));
contacts.add(new Contact("e#f.g", "8888"));
customerJpaProjection.findAll(QCustomerQueryData.customerQueryData.contact.in(contacts));
Not tested code.

EntityManager.getResultList() does not return the expected result

select a.AssignAccOwner,a.AssignBillRate,a.AssignPerdiem from orion_db.assignment as a where a.AssignmentId=25
I am able to execute the above query successfully . But when I try to execute the same query programatically using entityManager.createnativeQuery I am getting the resultList as 0
Below is the code
buff.append("select a.AssignAccOwner,a.AssignBillRate,a.AssignPerdiem from orion_db.assignment as a where a.AssignmentId=25");
Query q2 = entityManager.createNativeQuery(buff.toString());
resultList = q2.getResultList();
System.out.println("Geting the resultList in dao layer " + q2.getResultList().size());
System.out.println("Geting the result in dao layer " + resultList.size());
This is the result which I get in the log
Geting the resultList in dao layer 0
Geting the result in dao layer 0
Below is the assignment.java entity class
/**
* Assignment generated by hbm2java
*/
#Entity
#Table(name = "assignment")
public class Assignment implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer assignmentId;
private String assignAccOwner;
private BigDecimal assignBillRate;
private String assignPerdiem;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "AssignmentId", unique = true, nullable = false)
public Integer getAssignmentId() {
return this.assignmentId;
}
public void setAssignmentId(Integer assignmentId) {
this.assignmentId = assignmentId;
}
#Column(name = "AssignBillRate", precision = 10)
public BigDecimal getAssignBillRate() {
return this.assignBillRate;
}
public void setAssignBillRate(BigDecimal assignBillRate) {
this.assignBillRate = assignBillRate;
}
#Column(name = "AssignPerdiem", length = 30)
public String getAssignPerdiem() {
return this.assignPerdiem;
}
public void setAssignPerdiem(String assignPerdiem) {
this.assignPerdiem = assignPerdiem;
}
#Column(name = "AssignAccOwner", length = 100)
public String getAssignAccOwner() {
return this.assignAccOwner;
}
public void setAssignAccOwner(String assignAccOwner) {
this.assignAccOwner = assignAccOwner;
}
}
It was not the code issue , I was not connected to the local database and hence I was not getting the expected result..

Entity not posting to restful service

I'm having trouble posting a request to a restfull service.
It looks like my Entity is not getting converted into json correctly.
I get a 400 Bad request response.
I suspect it's the List of DateTimeRange objects causing the issue - as I have a very similar request that works but all the pojos properties are Strings.
Do I need to annotate my Entity to enable marshalling to/from json for Lists and my custom DateTimeRange?
String actionUrl = buildUrl( myResftullUrlTest );
Client client = ClientBuilder.newClient().register( JacksonJsonProvider.class );
Builder target = client.target( actionUrl ).request();
CreateWebinarRequest createWebinarRequest = new CreateWebinarRequest();
createWebinarRequest.setDescription("Test1 desc");
createWebinarRequest.setSubject("Test1 subject")
createWebinarRequest.setTimeZone("Europe/Dublin")
List<DateTimeRange> dateTimeRangeParam = new ArrayList<DateTimeRange>();
DateTimeRange dateTimeRange = new DateTimeRange();
dateTimeRange.setStartTime( "2016-11-03T08:34:12" );
dateTimeRange.setEndTime( "2016-11-03T09:34:12" );
dateTimeRangeParam.add( dateTimeRange );
createWebinarRequest.setTimes( dateTimeRangeParam );
Response response = null;
switch ( goToTrainingRequestData.getRequestType() ) {
case HTTP_POST :
response = target.buildPost( Entity.json(createWebinarRequest) ).invoke();
...
}
}
CreateWebinarRequest:
public class CreateWebinarRequest implements Serializable {
private String subject = null;
private String description = null;
private List<DateTimeRange> times = new ArrayList<DateTimeRange>();
private String timeZone = null;
public String getSubject() {
return subject;
}
public void setSubject( String subject ) {
this.subject = subject;
}
public String getDescription() {
return description;
}
public void setDescription( String description ) {
this.description = description;
}
public List<DateTimeRange> getTimes() {
return times;
}
public void setTimes( List<DateTimeRange> times ) {
this.times = times;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone( String timeZone ) {
this.timeZone = timeZone;
}
}
DateTimeRange:
public class DateTimeRange {
private String startTime = null;
private String endTime = null;
public String getStartTime() {
return startTime;
}
public void setStartTime( String startTime ) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime( String endTime ) {
this.endTime = endTime;
}
}
Problem solved guys and gals!
Nothing wrong with any data marshalling, I got the detailed response from server with:
String error = response.readEntity( String.class );
And it was a boo boo on my behalf!
{"errorCode":"RequestValidationError","description":"Request contains invalid parameters. See validationErrorCodes for specific errors.","Details":"times cannot be in past","incident":"6100682426566883853","validationErrorCodes":[{"code":"requestStartTimeInPast","description":"times cannot be in past"}]}

OrmLite Foreign Collection to List

I try to use foreign collections in ORMLite. However, I dont know how to convert it into list. I try to do something like this :
public class Car implements Serializable {
#DatabaseField(columnName = "carId" , generatedId = true, id=true)
private int id;
#DatabaseField(columnName = "carNumber")
private String mNumber;
#DatabaseField(columnName = "carName")
private String mName;
#ForeignCollectionField(eager = true,columnName = "carParts")
private Collection<Part> mParts;
ArrayList<Part> parts = new ArrayList<>(mParts);
public ArrayList<Part> getParts() {
return parts;
}
public void setParts(ArrayList<Part> parts) {
this.parts = parts;
}
but when I try to use it I get exception :
java.lang.NullPointerException: collection == null
at this line :
ArrayList<Part> parts = new ArrayList<>(mParts);
please, help.
The reason is simple - you have to wait until mParts will be initialized by ORMLite library, then you can create ArrayList from it.
public ArrayList<Part> getParts() {
return new ArrayList<>( mParts );
}