Null Pointer EmmbedId Class hashCode - orm

I am writing a play application with Basket, Product and Basket_Product tables. Basket and Products have a many to many relationship which is stored in Basket_Product. I am using Ebean ORM and am getting this error
[error] Test models.ModelsTest.createAndRetrieveOrder failed: java.lang.NullPointerException: null, took 5.128 sec
[error] at models.BasketProductPk.hashCode(BasketProductPk.java:43)
[error] at java.util.HashMap.hash(HashMap.java:338)
[error] at java.util.HashMap.get(HashMap.java:556)
[error] at com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext$ClassContext.putIfAbsent(DefaultPersistenceContext.java:175)
[error] at com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext$ClassContext.access$100(DefaultPersistenceContext.java:148)
[error] at com.avaje.ebeaninternal.server.transaction.DefaultPersistenceContext.putIfAbsent(DefaultPersistenceContext.java:56)
[error] at com.avaje.ebeaninternal.server.query.SqlTreeNodeBean.load(SqlTreeNodeBean.java:235)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readRow(CQuery.java:541)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readBeanInternal(CQuery.java:575)
[error] at com.avaje.ebeaninternal.server.query.CQuery.hasNextBean(CQuery.java:702)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readTheRows(CQuery.java:689)
[error] at com.avaje.ebeaninternal.server.query.CQuery.readCollection(CQuery.java:655)
[error] at com.avaje.ebeaninternal.server.query.CQueryEngine.findMany(CQueryEngine.java:175)
[error] at com.avaje.ebeaninternal.server.query.DefaultOrmQueryEngine.findMany(DefaultOrmQueryEngine.java:77)
[error] at com.avaje.ebeaninternal.server.core.OrmQueryRequest.findList(OrmQueryRequest.java:263)
[error] at com.avaje.ebeaninternal.server.core.DefaultServer.findList(DefaultServer.java:1502)
[error] at com.avaje.ebeaninternal.server.querydefn.DefaultOrmQuery.findList(DefaultOrmQuery.java:890)
[error] at com.avaje.ebeaninternal.util.DefaultExpressionList.findList(DefaultExpressionList.java:173)
[error] at models.ModelsTest.createAndRetrieveOrder(ModelsTest.java:100)
Here is my Junit test thats throwing the error. Its when i try accessing the Basket_Product table. I have checked my DB and everything inserts properly i just keep getting the error when trying to access Basket_Product for a specific basket.
Model Test Method
#Test
public void createAndRetrieveOrder(){
Customer walter = Customer.find.where().eq("email", "test#banana_now.com").findUnique();
Product p1 = Product.find.where().idEq(1).findUnique();
Product p2 = Product.find.where().idEq(2).findUnique();
Basket b = new Basket(walter);
b.save();
new BasketProduct(p1, b, 2).save();
new BasketProduct(p2, b, 2).save();
Basket b1 = Basket.find.where().idEq(8).findUnique();
List<BasketProduct> bplist = BasketProduct.find.where().eq("basket_id", b1.id).findList();
assertNotNull(bplist);
}
Embedded Key
#Embeddable
public class BasketProductPk implements Serializable{
#Column(name = "product_id")
private Product product;
#Column(name = "basket_id")
private Basket basket;
public BasketProductPk(Product product, Basket basket) {
this.product = product;
this.basket = basket;
}
#Override
public boolean equals(Object otherOb) {
if (this == otherOb) {
return true;
}
if (!(otherOb instanceof BasketProductPk)) {
return false;
}
BasketProductPk other = (BasketProductPk) otherOb;
return (
(product==null?other.product==null:product.equals
(other.product)
)
&&
(basket == other.basket)
);
}
#Override
public int hashCode() {
return (
(product==null?0:product.hashCode())
^
(basket.hashCode())
);
}
}
Basket Product
#Entity
#Table(name = "basket_product")
public class BasketProduct extends Model {
#EmbeddedId
public BasketProductPk id;
#ManyToOne(cascade= CascadeType.ALL)
#JoinColumn(name="product_id")
public Product product;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="basket_id")
public Basket basket;
public int quantity;
public float subtotal;
public BasketProduct(Product product, Basket basket, int quantity){
this.id = new BasketProductPk(product, basket);
this.product = product;
this.basket = basket;
this.quantity = quantity;
this.subtotal = quantity * product.price;
}
protected BasketProduct() {}
public static Finder<String, BasketProduct> find = new Finder<String, BasketProduct>(String.class, BasketProduct.class);
// getters, setters
}
Product
#Entity
public class Product extends Model{
#Id
public int id;
public String name;
public Float price;
public String category;
public String subcategory;
public String image_url;
public String url;
#ManyToOne
private Store store;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private List<BasketProduct> basket_product;
public Product(String name, Float price, String category, String subcategory, String image_url, String url, Store store){
this.name = name;
this.price = price;
this.category = category;
this.subcategory = subcategory;
this.image_url = image_url;
this.url = url;
this.store = store;
}
public static Finder<String, Product> find = new Finder<String, Product>(String.class, Product.class);
}
Basket
#Entity
public class Basket extends Model {
#Id
public int id;
#CreatedTimestamp
public Timestamp time;
int complete;
#ManyToOne
public Customer customer;
#ManyToOne
public Employee employee;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "basket")
public List<BasketProduct> basket_product;
public Basket(Customer customer){
this.customer = customer;
this.complete = 0;
}
public Basket(Customer customer, Employee employee){
this.customer = customer;
this.employee = employee;
}
public static Finder<String, Basket> find = new Finder<String, Basket>(String.class, Basket.class);
}

This error is because when BasketProductPk is loaded then Basket and Product are not loaded and they are both null.
I see that in your hashCode method you have:
(product==null?0:product.hashCode()) ^ (basket.hashCode())
So you check if product is null but you don't check if basket is null. So your NullPointerException is because basket is null.
To make this code work you have to make few changes in your code:
See these answers for details:
Example 1
Example 2
Example 3

Related

how do I resolve this problem use optaplanner

Here is a simple problem, some products, every product has a quantity, these products must be produced by some factories, and every factory has a max quantity ability, the product and the factory is a many to many relationship
Factory.class is
#Data
#AllArgsConstructor
public class Factory {
private String name;
private String code;
private Integer qty;
}
Product.class is
#Data
#AllArgsConstructor
public class Product {
private String name;
private String spuCode;
private Integer qty;
}
ProblemAndSolution.class is
#PlanningSolution
#Data
public class ProblemAndSolution {
#ProblemFactCollectionProperty
#ValueRangeProvider(id = "productList")
private List<Product> productList;
#ProblemFactCollectionProperty
#ValueRangeProvider(id = "factoryList")
private List<Factory> factoryList;
private List<ProductFactoryAssignment> solutionList;
#PlanningScore
private HardSoftScore score;
#PlanningEntityCollectionProperty
public List<ProductFactoryAssignment> getSolutionList() {
return solutionList;
}
}
ProductFactoryAssignment.class is
#Data
#PlanningEntity
#AllArgsConstructor
public class ProductFactoryAssignment {
#PlanningVariable(valueRangeProviderRefs = "productList")
private Product product;
#PlanningVariable(valueRangeProviderRefs = "factoryList")
private Factory factory;
private Integer qty;
public Product getProduct() {
return product;
}
public Factory getFactory() {
return factory;
}
public Integer getQty() {
return qty;
}
#Override
public String toString() {
return "product is:" + product.getName() + ",factory is:"+factory.getName()+",qty is:"+qty;
}
}
ProductFactoryConstraintProvider.class is
public class ProductFactoryConstraintProvider implements ConstraintProvider {
#Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[] {
// Hard constraints
productQtyConflict(constraintFactory),
factoryQtyConflict(constraintFactory)
};
}
Constraint productQtyConflict(ConstraintFactory constraintFactory) {
return constraintFactory
.forEach(ProductFactoryAssignment.class)
.groupBy(ProductFactoryAssignment::getProduct, ConstraintCollectors.sum(ProductFactoryAssignment::getQty))
.filter((product, poQty) -> poQty >= product.getQty())
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("error");
}
Constraint factoryQtyConflict(ConstraintFactory constraintFactory) {
return constraintFactory
.forEach(ProductFactoryAssignment.class)
.groupBy(ProductFactoryAssignment::getFactory, ConstraintCollectors.sum(ProductFactoryAssignment::getQty))
.filter((factory, poQty) -> poQty <= factory.getQty())
.penalize(HardSoftScore.ONE_HARD)
.asConstraint("error");
}
}
main is
public static void main(String[] args) {
SolverFactory<ProblemAndSolution> solverFactory = SolverFactory.create(new SolverConfig()
.withSolutionClass(ProblemAndSolution.class)
.withEntityClasses(ProductFactoryAssignment.class)
.withConstraintProviderClass(ProductFactoryConstraintProvider.class)
// The solver runs only for 5 seconds on this small dataset.
// It's recommended to run for at least 5 minutes ("5m") otherwise.
.withTerminationSpentLimit(Duration.ofSeconds(5)));
// Load the problem
ProblemAndSolution problem = new ProblemAndSolution();
List<Product> productList = Lists.newArrayList(
new Product("product1", "001", 10000),
new Product("product2", "002", 5000)
);
List<Factory> factoryList = Lists.newArrayList(
new Factory("factory1", "001", 3000),
new Factory("factory2", "002", 6000),
new Factory("factory3", "003", 7000),
new Factory("factory4", "004", 4000),
new Factory("factory5", "005", 3000)
);
problem.setProductList(productList);
problem.setFactoryList(factoryList);
problem.setSolutionList(Lists.newArrayList());
// Solve the problem
Solver<ProblemAndSolution> solver = solverFactory.buildSolver();
ProblemAndSolution solution = solver.solve(problem);
System.out.println(solution);
}
solution's solutionList is empty, how to get a result like
product1, factory1, 3000
product1, factory3, 7000
product2, factory2, 5000
You have not filled the solution list with any planning entities, therefore OptaPlanner does not have anything to solve. Introduce some planning entity instances, and OptaPlanner will assign their planning variables with the values from the factory and product lists.
(Note: I'm not saying the domain model is correct or that it will do what you want it to do. I'm just saying that, without planning entities, it will not do anything at all.)

No property 'birthDate' found for type 'person'! Did you mean ''birthdate''? in srping boot

I am developing and rest api and i want to filter a data by birthday. I create birthday variable as birthday in every where and when i compile my code i get an error that " No property 'birthDate' found for type 'person'! Did you mean ''birthdate''?". But i haven't make a variable as birthDate
entity
public class person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY )
private long id;
#Column(name="Name")
private String name ;
#Column(name="surname")
private String surname;
#Column(name="Birthdate")
#JsonFormat(pattern = "yyyy-MM-dd")
private Date birthdate;
#OneToMany(targetEntity = address.class, cascade = CascadeType.ALL)
#JoinColumn(name ="per_id", referencedColumnName = "id")
private List<address> address = new ArrayList<>();
}
repository
public interface personRepository extends JpaRepository<person,Long> {
public List<person> findByName(String Name);
public List<person> findByBirthDate(Date birthdate);
}
controller
#GetMapping()
public List filterall(#RequestParam(required = false) String name, #RequestParam(required = false) Date birthdate){
//return null;
var personsByName = repository.findByName(name);
var personsByBday= repository.findByBirthDate(birthdate);
return personsByBday;
}
error!

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum

I get this error while trying to persist an entity 'UserAccount' into the database table.
#Entity
#Table(name = "user_account")
public class UserAccount extends BaseEntity {
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "useraccount_id")
#MapKeyEnumerated(EnumType.STRING)
private Map<PhoneType, PhoneNumber> phones = new HashMap<PhoneType, PhoneNumber>();
//... other attributes
//... default constructor, getters and setters
}
public enum PhoneType {
HOME("home"),
MOBILE("mobile"),
FAX("fax"),
WORK("work");
private String value;
PhoneType(String value) {
this.value = value;
}
#JsonValue
public String getValue() {
return value;
}
}
#Entity
#Table(name = "phone_number")
public class PhoneNumber extends BaseEntity {
private String areaCode;
private String number;
//... default constructor, getters and setters
}
and finally..
public class UserAccountRepository {
#Inject
EntityManager entityManager;
#Override
public UserAccount save(UserAccount userAccount) {
if (userAccount.getId() == null) {
entityManager.persist(userAccount);
} else {
userAccount = entityManager.merge(userAccount);
}
return userAccount;
}
//.. other methods
}
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum
at org.eclipse.persistence.mappings.converters.EnumTypeConverter.convertObjectValueToDataValue(EnumTypeConverter.java:165)
at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.extractIdentityFieldsForQuery(AbstractDirectMapping.java:568)
at org.eclipse.persistence.internal.queries.MappedKeyMapContainerPolicy.getKeyMappingDataForWriteQuery(MappedKeyMapContainerPolicy.java:145)
at org.eclipse.persistence.mappings.OneToManyMapping.updateTargetRowPostInsertSource(OneToManyMapping.java:1425)
at org.eclipse.persistence.mappings.OneToManyMapping.performDataModificationEvent(OneToManyMapping.java:936)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:162)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4387)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1493)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1583)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3258)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:357)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:160)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:70)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
... 94 more
Other questions with same error suggest to add #Enumerated(EnumType.STRING) on the attribute of type Enum, I have used #MapKeyEnumerated(EnumType.STRING) on the phones Map, but I still see get this error. Any clues where am I wrong?
Please let me know if I haven't asked the question as per the SO guidance, I will correct it (as this is my 1st question).
I made a change to the PhoneNumber class as below
#Entity
#Table(name = "phone_number")
public class PhoneNumber extends BaseEntity {
private PhoneType type;
private String areaCode;
private String number;
//... default constructor, getters and setters
}
and then added #MapKey(name = "type") in the UserAccount as below.
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "useraccount_id")
#MapKeyEnumerated(EnumType.STRING)
#MapKey(name = "type")
private Map<PhoneType, PhoneNumber> phones = new HashMap<PhoneType, PhoneNumber>();
With these changes I am now able to save the UserAccount object successfully into the db tables.

Different Result Set While using Criteria vs just Create Query

Manual Method without criteriaQuery
I have used this code to get result set which contains of Thirdparty by using a left join with another table ThirdPartyHasOwner which has two primary keys and is a foreign key itself. Now the below code retrieves the correct result data set.
Query query = emManager.createQuery("SELECT c FROM ThirdParty c LEFT JOIN ThirdPartyHasOwner b ON b.id.third_party_Id = c.id WHERE b.id.ownerId=1");
List<ThirdParty> thirdParties = query.getResultList();
With Criteria Builder and Criteria Query
But When using with the criteria builder and Query the result set gives a wrong dataset. The code is given below So to check whether both above manual query and criteria query gives the same query I added Property <property name="eclipselink.logging.level" value="FINE"/> for which both the above code without criteria query and the below code with criteria query both gave the same query Both the code and console result are given below
CriteriaBuilder cb = emManager.getCriteriaBuilder();
CriteriaQuery<ThirdParty> cq = cb.createQuery(ThirdParty.class);
Root<ThirdParty> a = cq.from(ThirdParty.class);
Join<ThirdParty, ThirdPartyHasOwner> b = a.join("thirdPartyHasOwners", JoinType.LEFT);
ParameterExpression<Integer> balance = cb.parameter(Integer.class);
Path<Integer> path = b.get("id").get("ownerId");
cq.where(cb.gt(path, balance));
cq.select(a);
TypedQuery<ThirdParty> queryS = emManager.createQuery(cq);
List<ThirdParty> results = queryS.setParameter(balance, 1).getResultList();
The Console result (The first one is for the Criteria Query and the second one is for the manual method)
[EL Fine]: sql: 2017-01-04 06:42:44.026--ServerSession(514728045)--Connection(1288428548)--Thread(Thread[http-bio-8080-exec-3,5,main])--SELECT t1.Id, t1.ADDRESS, t1.CONTACTNO, t1.CREATEDDATE, t1.EMAIL, t1.NAME FROM third_party t1 LEFT OUTER JOIN third_party_has_owner t0 ON (t0.THIRD_PARTY_ID = t1.Id) WHERE (t0.owner_id > ?)
bind => [1]
[EL Fine]: sql: 2017-01-04 06:48:26.109--ServerSession(514728045)--Connection(1288428548)--Thread(Thread[http-bio-8080-exec-3,5,main])--SELECT t1.Id, t1.ADDRESS, t1.CONTACTNO, t1.CREATEDDATE, t1.EMAIL, t1.NAME FROM third_party t1 LEFT OUTER JOIN third_party_has_owner t0 ON (t0.THIRD_PARTY_ID = t1.Id) WHERE (t0.owner_id = ?)
bind => [1]
result for both manual and criteria query (result variable has the wrong data which is the result of using criteria query and thirdparties variable has the correct data set which is the result of the manual method)
Last but not least I am using javax.persistence.persistence-api which is eclipselink
This is the overview of the Database tables
Model Class For Third Party
/**
* The persistent class for the third_party database table.
*
*/
#Entity
#Table(name="third_party")
#NamedQuery(name="ThirdParty.findAll", query="SELECT t FROM ThirdParty t")
public class ThirdParty implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="Id")
private int id;
private String address;
private String contactNo;
#Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
private String email;
private String name;
//bi-directional many-to-one association to ThirdPartyHasOwner
#OneToMany(mappedBy="thirdParty")
private List<ThirdPartyHasOwner> thirdPartyHasOwners;
//bi-directional many-to-one association to ThirdSeatAllocation
#OneToMany(mappedBy="thirdParty")
private List<ThirdSeatAllocation> thirdSeatAllocations;
public ThirdParty() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactNo() {
return this.contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public List<ThirdPartyHasOwner> getThirdPartyHasOwners() {
return this.thirdPartyHasOwners;
}
public void setThirdPartyHasOwners(List<ThirdPartyHasOwner> thirdPartyHasOwners) {
this.thirdPartyHasOwners = thirdPartyHasOwners;
}
public ThirdPartyHasOwner addThirdPartyHasOwner(ThirdPartyHasOwner thirdPartyHasOwner) {
getThirdPartyHasOwners().add(thirdPartyHasOwner);
thirdPartyHasOwner.setThirdParty(this);
return thirdPartyHasOwner;
}
public ThirdPartyHasOwner removeThirdPartyHasOwner(ThirdPartyHasOwner thirdPartyHasOwner) {
getThirdPartyHasOwners().remove(thirdPartyHasOwner);
thirdPartyHasOwner.setThirdParty(null);
return thirdPartyHasOwner;
}
public List<ThirdSeatAllocation> getThirdSeatAllocations() {
return this.thirdSeatAllocations;
}
public void setThirdSeatAllocations(List<ThirdSeatAllocation> thirdSeatAllocations) {
this.thirdSeatAllocations = thirdSeatAllocations;
}
public ThirdSeatAllocation addThirdSeatAllocation(ThirdSeatAllocation thirdSeatAllocation) {
getThirdSeatAllocations().add(thirdSeatAllocation);
thirdSeatAllocation.setThirdParty(this);
return thirdSeatAllocation;
}
public ThirdSeatAllocation removeThirdSeatAllocation(ThirdSeatAllocation thirdSeatAllocation) {
getThirdSeatAllocations().remove(thirdSeatAllocation);
thirdSeatAllocation.setThirdParty(null);
return thirdSeatAllocation;
}
}
Model Class For Third Party has Owner
/**
* The persistent class for the third_party_has_owner database table.
*
*/
#Entity
#Table(name="third_party_has_owner")
#NamedQuery(name="ThirdPartyHasOwner.findAll", query="SELECT t FROM ThirdPartyHasOwner t")
public class ThirdPartyHasOwner implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private ThirdPartyHasOwnerPK id;
#Temporal(TemporalType.DATE)
private Date createdDate;
//bi-directional many-to-one association to Owner
#ManyToOne
private Owner owner;
//bi-directional many-to-one association to ThirdParty
#ManyToOne
#JoinColumn(name="third_party_Id")
private ThirdParty thirdParty;
public ThirdPartyHasOwner() {
}
public ThirdPartyHasOwnerPK getId() {
return this.id;
}
public void setId(ThirdPartyHasOwnerPK id) {
this.id = id;
}
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public Owner getOwner() {
return this.owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public ThirdParty getThirdParty() {
return this.thirdParty;
}
public void setThirdParty(ThirdParty thirdParty) {
this.thirdParty = thirdParty;
}
}
So Did I do something wrong with the criteria query or is it some weird bug?
Though the log was fine still I have used a different method which gives the different data set.
Before Code
CriteriaBuilder cb = emManager.getCriteriaBuilder();
CriteriaQuery<ThirdParty> cq = cb.createQuery(ThirdParty.class);
Root<ThirdParty> a = cq.from(ThirdParty.class);
Join<ThirdParty, ThirdPartyHasOwner> b = a.join("thirdPartyHasOwners", JoinType.LEFT);
ParameterExpression<Integer> balance = cb.parameter(Integer.class);
Path<Integer> path = b.get("id").get("ownerId");
cq.where(cb.gt(path, balance));
cq.select(a);
TypedQuery<ThirdParty> queryS = emManager.createQuery(cq);
List<ThirdParty> results = queryS.setParameter(balance, 1).getResultList();
After Code
CriteriaBuilder cb = emManager.getCriteriaBuilder();
CriteriaQuery<ThirdParty> cq = cb.createQuery(ThirdParty.class);
Root<ThirdParty> a = cq.from(ThirdParty.class);
Join<ThirdParty, ThirdPartyHasOwner> b = a.join("thirdPartyHasOwners", JoinType.LEFT);
ParameterExpression<Integer> balance = cb.parameter(Integer.class);
cq.where(cb.equal( b.get("id").get("ownerId"),balance));
cq.select(a);
TypedQuery<ThirdParty> queryS = emManager.createQuery(cq);
List<ThirdParty> results = queryS.setParameter(balance, 1).getResultList();
The code which is being changed is cq.where(cb.gt(path, balance)); to cq.where(cb.equal( b.get("id").get("ownerId"),balance)); for criteria builder equal is used here is equal to Where b.owner_id = balance balance is a parameter

Hibernate queryexception: could not resolve entity property during JPA query

I am trying to query my hibernate table for a RunEntity. The first where clause in the query searches for RunEntities where the testName = the passed value testname. In the stacktrace, it mentions that it cannot find a match for type testname in the RunEntity, but the RunEntity object explicitly has a string named testName with setters and getters and #Column notation.
Table setup
CREATE TABLE RunEntity (ID INTEGER IDENTITY,TestNumber INTEGER NOT NULL, TestName varchar(50) NOT NULL, ENVIRONMENT VARCHAR(50) NOT NULL, Source VARCHAR(50), Date TIMESTAMP, RESULTFILES BLOB);
Query
#Query("SELECT r FROM RunEntity r WHERE r.testName = :testname AND r.testNumber = :testnumber AND r.environment = :environment AND r.source = :source")
public List<RunEntity> findByNameNumberEnvironmentSource(
#Param("testname") String testname,
#Param("testnumber") int testnumber,
#Param("environment") String environment,
#Param("source") String source);
Entity
package com.web_application;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Lob;
#Entity
#Table(name = "TESTRUNS")
public class RunEntity {
private int ID;
private int testNumber;
private String testName;
private String environment;
private String source;
private String passOrFail;
private Timestamp date;
private byte[] resultFiles;
#Id
#Column(name = "ID")
#GeneratedValue
public int getID()
{
return this.ID;
}
public void setID(int ID){this.ID = ID;}
#Column(name="TestNumber")
public int getTestNumber()
{
return this.testNumber;
}
public void setTestNumber(int testNum){this.testNumber = testNum;}
#Column(name="TestName")
public String testName()
{
return this.testName;
}
public void setTestName(String testName){this.testName = testName;}
#Column(name="Environment")
public String getEnvironment()
{
return this.environment;
}
public void setEnvironment(String enviro){this.environment = enviro;}
#Column(name="Source")
public String getSource()
{
return this.source;
}
public void setSource(String src){this.source = src;}
#Column(name="PassOrFail")
public String getPassOrFail()
{
return this.passOrFail;
}
public void setPassOrFail(String pOrF){this.passOrFail = pOrF;}
#Column(name="Date")
public Timestamp getDate()
{
return this.date;
}
public void setDate(Timestamp dates){this.date = dates;}
#Lob
#Column(name="ResultFiles")
public byte[] getResultFiles()
{
return this.resultFiles;
}
public void setResultFiles(byte[] file){this.resultFiles = file;}
}
Part of stacktrace
Caused by: org.hibernate.QueryException: could not resolve property: testname of: com.web_application.RunEntity [SELECT r FROM com.web_application.RunEntity r WHERE r.testname = :testname AND r.testNumber = :testnumber AND r.environment = :environment AND r.source = :source]
at org.hibernate.QueryException.generateQueryException(QueryException.java:137)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328)
... 66 more
Change this
#Column(name="TestName")
public String testName()
{
return this.testName;
}
to
#Column(name="TestName")
public String getTestName()
{
return this.testName;
}
Property access Naming convention is important.Try to use IDE for example (Eclipse Getter-Setter,instead using manually doing it)
Correct your testName() getter to getTestName(). You are using Property Access and have to stick to JavaBeans convention.