org.hibernate.ObjectNotFoundException issue with using list() - java

The following query throws the exception:
Query query = session.createQuery("from Associate as a order by a.username asc");
associates = query.list();
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ca.mypkg.model.Associate#0]
If I create an entry in the database with id of 0 it works just fine. I don't really get it because I'm just trying to load all the entries in the db not just a specific one.
Similar questions I've found have been concerned with trying to load an object with a given ID I'm doing no such thing.
Associate class:
#Table(name = "user")
#XmlRootElement(name = "associate")
public class Associate implements Serializable {
private String username;
private String password;
private String firstName;
private String lastName;
private String userType;
private int id;
private String email;
private String isActive;
private Department dept;
private String lastUpdated;
private String associate_type;
// ...
#Id
#GeneratedValue
public int getId() {
return id;
}
#OneToOne
#JoinColumn(name = "dept")
public Department getDept() {
return dept;
}

From my experience this type of error message usually means it does not find joined entity by mentioned id, and not the entity requested in the query (Associate, in your case).
My guess is that Associate class contains a join entity which has primitive type primary key.

Related

How to get Entity based on member object's field value rather than member objects ID

I have three classes and code for the same is displayed below
Enquiry Class:
#Entity
public class Enquiry
{
#Id
#GeneratedValue
private int id;
private String name;
private String discription;
private int status;
#Temporal(TemporalType.DATE)
private Date enquiryDate;
}
User Class:
#Entity
public class User
{
#Id
#GeneratedValue
private int id;
private String name;
private String userId;
private String password;
}
UserEnquiryUserEnquiryMapping Class:
#Entity
public class UserEnquiryMapping
{
#Id
#GeneratedValue
private int id;
#ManyToOne
private User user;
#ManyToOne
private Enquiry enquiry;
}
Now suppose if we want to get Enquiry(s) for a particular User than we can easily get it by passing a User object and hibernate will generate query by using id field from User object, and code for the same scenario is mentioned below.
EntityManager entityManager = session.getEntityManagerFactory().createEntityManager();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<UserEnquiryMapping> criteria = builder.createQuery(UserEnquiryMapping.class);
Root<UserEnquiryMapping> root = criteria.from(UserEnquiryMapping.class);
criteria.select(root);
criteria.where(builder.equal(root.get("user"), user));
userEnquiries = entityManager.createQuery(criteria).getResultList();
But my requirement is I want to get User enquiries on the basis of user's name or we can say that I want to generate query like this
Select * from UserEnquiryMapping inner join Enquiry on UserEnquiryMapping.Enquiry_ID = Enquiry.ID inner join User on UserEnquiryMapping.User_ID = User.ID where User.name="Test";
How can I do this?
builder.equal(root.get("user").get("name"),user.getName());
glad it help you!

Query multi tables' columns with join in spring data jpa

Description:
I have two tables, Shop_Employee and Shop_Employee_Type. I wanna display typeName directly when show the employee detail information, but I don't want to config the relationship(OneToMany or ManyToOne) between this two entity. Because this will load all Shop_Employee_Type column's value, but these values are useless for me, I just need typeName of Shop_Employee_Type.
Below is my code, but it doesn't work.
ShopEmployeeType:
#Entity
#Data
//#DynamicUpdate
public class ShopEmployeeType {
#Id
private String typeId;
private String shopId;
private String typeName;
private Integer typeStatus;
private String typeDescription;
}
Shop_Employee:
#Entity
#Data
public class ShopEmployee {
#Id
private String employeeId;
private String shopId;
private String typeId;
private String name;
private String code;
private String phone;
private Integer status;
private String idcardNumber;
private String image;
//#Transient
private String typeName;
public ShopEmployee() {
}
}
Repository:
#Query(value = "select u.*,t.type_name from shop_employee u inner join shop_employee_type t on u.type_id=t.type_id", nativeQuery = true)
List<ShopEmployee> findAllData();
This could show typeName as I wished, but there is an error appears when I save a new entity Shop_Employee; If I add a #Transient for 'typeName', It could save successfully, but the value of 'typeName' is null when I query entity Shop_Employee.
Your query should return two Objects Shop_Employee and a String, so the return results should not be List<ShopEmployee> it should be :
#Query(value = "select u.*, t.type_name from shop_employee ...", nativeQuery = true)
List<Object[]> findAllData();
Then you can get the ShopEmployee using :
List<Object[]> list = findAllData();
for(Object[] obj : list){
ShopEmployee shopEmployee = (ShopEmployee) obj[0];
String type_name = (String) obj[1];
}
So, in ShopEmployee entity you don't need to use :
//#Transient
//private String typeName;

Correct way to get model list in another model

I am working on a spring mvc app in which there are 2 entities, contact and location. Following are my contact and location models:
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#Column(name="locationid")
private int locationId;
}
Location model:
#Entity
#Table(name="Location")
public class LocationModel {
#Id
#Column(name="locationid")
#GeneratedValue
private int locationId;
#Column(name="locationname")
private String locationName;
#Column(name="locationdesc")
private String locationDescription;
#Column(name="type")
private String locationType;
#Column(name="address")
private String address;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="district")
private String district;
#Column(name="lattitude")
private String lattitude;
#Column(name="longitude")
private String longitude;
}
In contact dao, I am getting contact list using below code:
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ContactModel.class);
criteria.addOrder(Order.asc("contactName"));
return criteria.list();
Now I need to show contact list on contact home page which will show contact name and its corresponding location name.
To show the contact list, I need to create join in contact and location tables. Is this the proper way? How can we do this in hibernate?
Also is it the proper way to add location entity in contact entity, or do I have to use location model in contact?
You have to relate your both entities with relation .I am assuming that ContactModel have One-To-One relation with LocationModel
Change your ContactModel to
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#OneToOne
#Column(name="locationid")
private LocationModel location;
}
and do the rest of thing same as you are doing select only the ContactModel List objects.
public List<ContactModel> allContactModel(){
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(ContactModel.class);
criteria.addOrder(Order.asc("contactName"));
return criteria.list();
}
and get the value of location in your controller by iterating over list ContactModel and fetch the LocationModel object from ContactModel as you fetch normal variable by ClassName.Fieldname.Here It will Give you a LocationModel object
List<ContactModel> mylist=ContactModel.allContactModel();
for(ContactModel cm: mylist){
LocationModel lm=ContactModel.getLocationModel();
System.out.println(cm.getContactName+" location is "+lm.getLocationName);
}
Now you have the LocationModel, you can fetch its further values also.
You can also further enhance this onetoone relation by specifying fetchtype,cascadetype etc accoding to your requirements.
Note:Assuming that you are have getter and setter in your model
i think the right way is that the contact can have a location, now add a location object to your contact, something like this:
#Entity
#Table(name="Contact")
public class ContactModel {
...
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinColumn(name = "locationid", nullable = false)
private LocationModel location;
// can be removed
#Column(name="locationid")
private int locationId;
...
}
if you have this you get the location object when you call a contact record

Create new object from two tables JDO DataNucleus

I am attempting to create a DTO object by persisting two classes using DataNucleus.
The DTO I wish to create:
#PersistenceAware
DtoObject{
Protected String Id; //populated by Order class
Protected String status; //populated by Order class
Protected String phoneNumber; //populated by Customer class
Protected String address; //populated by Customer class
}
The Objects:
#PersistenceCapable
#FetchGroup(name="dto", members = {#Persistent(name = "Id"),
#Persistent(name="status")})
public Class Order{
#PrimaryKey
#Persistent
private String Id;
#Persistent
private String status;
#Persistent
private Customer customer;
}
#PersistenceCapable
#FechGroup(name="dto", members = { #Persistent(name = "phoneNumber"),
#Peristent(name="address") })
public Class Customer{
#PrimaryKey
#Persistent
private String Id;
#Persistent
private String phoneNumber;
#Persistent
private string Address;
}
The JDODL:
Query q = pm.newQuery(Order.class);
pm.getFetchPlan().setGroup("dto");
q.setUnique(true);
q.setFilter("Id == id");
q.declareParameters("String id");
q.setResultClass(DtoObject.class);
DtoObject dto = (DtoObject)q.execute(id);
I can populate the dto object with its attributes mapped to the Order.class but can not get the attributes from the Customer.class. Data Nucleus joins the tables and selects the proper columns from each table but leaves the phoneNumber =null and address = null;
Pointers on how to make this work with one query will be appreciated.
Query q = pm.newQuery("SELECT UNIQUE this.id, this.status, " +
" this.customer.phoneNumber, this.customer.address INTO " +
DtoObject.class.getName() +
" FROM " + Order.class.getName() + " WHERE this.id = :id");
DtoObject dto = (DtoObject)q.execute(idParam);
Assuming the result class (DtoObject) obeys the conditions of a result class

JPA #SecondaryTables, why my primary table is empty? While the secondary tables is not empty?

I've simple POJO like :
#Entity
#Table(name = "t_address")
#SecondaryTables({
#SecondaryTable(name="t_city"),
#SecondaryTable(name="t_country")
})
public class Address{
#Id
#GeneratedValue
private Long id;
private String street1;
private String street2;
#Column(table="t_city")
private String city;
#Column(table="t_city")
private String state;
#Column(table="t_city")
private String zipcode;
#Column(table="t_country")
private String country;
// setter - getter
}
And then in my Main class, i've an instance like :
Address address = new Address();
address.setStreet1("boulevard of broken dream");
address.setStreet2("abbey road");
address.setCity("San Fransisco");
address.setState("California");
address.setZipcode("13460");
address.setCountry("USA");
// some variable declaration
tx.begin();
em.persist(address);
tx.commit();
After execute the Main class, i've 3 tables inside the database there are:
t_address [ID,STREET1,STREET2]
t_city [ID, CITY, STATE, ZIPCODE]
t_country [ID,COUNTRY]
After query every table, why the data only store in t_city and t_country, NOT in t_address? Can you explain the reason?

Categories

Resources