In hibernate, for example I have two object which has relation. The object is like this
First object : Customer
#Entity
#Table(name = "customer", catalog = "test")
public class Customer implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Set<CustomerController> customerControllers = new HashSet<CustomerController>(0);
public Customer() {
}
//getter & setter
}
Second Object : CustomerController
#Entity
#Table(name = "customer_controller", catalog = "test")
public class CustomerController implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Customer customer;
//constructor, getter & setter
}
I want to select the customer_controller of certain customer. I get it by two manner. First manner :
#Override
public List<CustomerController> customerController(int customerId){
Customer customer = (Customer) sessionFactory.getCurrentSession().get(Customer.class, customerId);
return customer.getCustomerControllers()
}
Second manner :
return (List<CustomerController>)sessionFactory.getCurrentSession().createQuery("SELECT O FROM CustomerController O WHERE O.customerId=:CONDITION")
.setParameter("CONDITION", customerId)
.list();
Which manner is the most efficient one? Why?
Thank you.
To ensure it is easier to "turn on" show SQL parameter and monitor it.
I suppose in first hibernate able to generate two SQL query with entity mapping.
In second case should be generated only one select query.
In case when we use FetchType.EAGER think Hibernate will map Customer and CustomerController entity. Hope Hibernate fetch only CustomerController using HQL. To ensure you should monitor Hibernate behavior.
Related
I have a business in which I have agencies and backlogs. One Agency has one backlog.
I have a query that allow me to retrieve all agencies, but I get an NPE when trying to access backlog of the agencies retrieved.
When I get a saved object in JPA, shouldn't I have the associated objects as well ?
Here are my entities and service:
Agency
#NamedQuery(name="allAgences", query="select a from Agency a")
#Stateless
#Entity
public class Agency implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
private int id;
private String name;
#OneToOne(optional = true, orphanRemoval = true,
cascade=CascadeType.ALL, mappedBy="agency",
targetEntity=Backlog.class )
private Backlog backlog;
public Agency(String name, Backlog backlog) {
this.name = name;
this.backlog = backlog;
}
public Agency() {
this.setName("");
this.setBacklog(new Backlog());
}
}
// getters, setters...
Backlog
#Stateless
#Entity
public class Backlog implements Serializable {
private static final long serialVersionUID = 1L;
Id
#GeneratedValue
private int id;
#OneToOne(optional = true)
#JoinColumn(name = "agency_id")
private Agency agency;
public Backlog() {}
//getters, setters....
}
My Ejb Service
#Stateless
#LocalBean
public class AgencyBean implements AgencyBeanRemote {
#PersistenceContext
private EntityManager em;
/**
* Default constructor.
*/
public AgencyBean() {}
#Override
public Agency createAgency(String agencyName) {
Agency agency = new Agency();
agency.setBacklog(new Backlog());
agency.getBacklog().setEntries(new ArrayList<>());
agency.setName(agencyName);
em.getTransaction().begin();
em.persist(agency);
em.getTransaction().commit();
return agency;
}
#Override
public List<Agency> getAllAgencies() {
Query q = em.createNamedQuery("allAgences");
List<Agency> agencies = q.getResultList();
for(Agency agency : agencies) {
// System.out.println("hello " + agency.getBacklog().getId());
// give me a NPE
}
return agencies;
}
}
I guess that the NPE is because backlog is null in agency.getBacklog().getId()
If you take a look on the database and table backlog I think you see that agency_id is null. Therefore Backlogs cannot be attached to Agency.
To fix this change - in your public createAgency(String agencyName)- row
agency.setBacklog(new Backlog());
to rows
Backlog backlog = new Backlog();
agency.setBacklog(backlog);
backlog.setAgency(agency); // this should do the fix
And just to mention - namely if I guessed the NPE reason correct - you have
#OneToOne(optional = true ...
private Backlog backlog;
so you should expect backlog also to be null but you do not check that in your code? (Yes I realize that it is possibly only for a test purposes but just to to mention)
Related: Persist OneToOne relation
Update
In Entity Agency you can also implement following
#PrePersist
private void prePersist() {
// add needed NPE checks etc...
backlog.setAgency(this);
}
This might reduce boilerplate code since there is no more need to add this backlog.setAgency(agency) everywhere Agency is created the way you do it.
I'm new here and I'm also new in JPA! I developed a little JPA Application with the following entities:
A Customer(Name, Prename, ID) has got an Address(ZIP_Code, city, ID). The relation between these entities is ManyToOne (Customer's perpective) and OneToMany (Address' perspective).
The code (parts) are the following: (without getters/setters)
#Entity
public class AddressEntity implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String city;
private int zipCode;
#Column
#ElementCollection(targetClass=CustomerEntity.class)
private List<CustomerEntity> customers;
public AddressEntity() {}
#OneToMany(cascade=CascadeType.ALL,
fetch=FetchType.EAGER,
mappedBy="addressentity")
public List<CustomerEntity> getCustomers() {
return customers;
}
#Entity
public class CustomerEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int primaryKey;
private String preName, surName;
#ManyToOne(targetEntity=AddressEntity.class, cascade=CascadeType.ALL)
#JoinColumn(name="Address_ID")
private AddressEntity address;
public CustomerEntity() {}
}
Now i want to add two persons:
1) Bart Simpson 1234 Springfield
2) Homer Simpson 1234 Springfield
The problem is that in the address table Springfield appears twice. But that's not the sense of normalized database! How can I realize that an AddressEntity is only added when it does not exists before!
Thanks for answering,
eniac
Persisting new addresses
It is possible to have many AddressEntities with the same City and Zipcode. If you require that a given CustomerEntity is related to the same address, then you must use that specific entity. So use the same AddressEntity that you used for Bart for Homer also
CustomerEntity bart = new CustomerEntity();
//Set Barts’s fields.
CustomerEntity homer = new CustomerEntity();
//Set Homers’s fields.
AddressEntity simpsonsPlace = new AddressEntity();
//set 1234 and Springfield.
bart.setAdress(simpsonsPlace);
homer.setAdress(simpsonsPlace);
List<CustomerEntity> simpsons = new ArrayList<CustomerEntity>();
simpsons.add(bart);
simpsons.add(homer);
simpsonsPlace.setCustomers(simpsons);
yourEntityManager.persist(bart);
yourEntityManager.persist(homer);
Associating with existing addresses.
If you are creating homer sometime after bart then you will want to associate bart to an existing address. It maybe that you will pass in the address from the client. This will have the id field populated and will be a detached entity. You can use this entity with the em.merge() operation;
CustomerEntity homer = new CustomerEntity();
homer.setAdress(detachedAddress);
yourEntityManager.merge(homer);
A better way might be to form a compound PK of Zip/HouseNumber for example. This ensures that any AddressEntity with Zip/HouseNumber combination already in the DB will be treated as a detached object, and will of course only appear once in the DB.
Embeddables
You have both #ElementCollection and #OneToMany targeted to your CustomerEntity Entity.
As per JPA Spec 11.1.14;
The ElementCollection annotation defines a collection of instances of
a basic type or embeddable class.
It is therefore incorrect to target an entity with #ElementCollection.
You require a relation between your two entities, therefore, in you your AddressEntity you just need to use the #OneToMany and drop the #ElementCollection. You also need to map (with mappedBy) to the field of the target class and not the target class itself;
#Entity
public class AddressEntity implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String city;
private int zipCode;
#OneToMany(cascade=CascadeType.ALL,
fetch=FetchType.EAGER,
mappedBy="address") //Not addressentity
private List<CustomerEntity> customers;
public AddressEntity() {}
public List<CustomerEntity> getCustomers() {
return customers;
}
Alternatively you can define your CustomerEntity as an #Embeddable and not an #entity. In this way you can use #ElementCollection to target CustomerEntity from AddressEntity, but CustomerEntity would not be an entity in its own right and cannot be processed independently as it is dependent on AddressEntity
I would like to find an entity using a critera with restriction on the value of an attribute of a second entity wich is a member of the embedded id of my first entity.
First entity :
#Entity
public class Car {
#EmbeddedId
private Id id = new Id();
private String color;
#Embeddable
public static class Id implements Serializable {
private static final long serialVersionUID = -8141132005371636607L;
#ManyToOne
private Owner owner;
private String model;
// getters and setters...
// equals and hashcode methods
}
// getters and setters...
}
Second entity :
#Entity
public class Owner {
#Id
#GeneratedValue (strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
#OneToMany (mappedBy = "id.owner")
private List<Car> cars;
// getters and setters...
}
In this example, I would like to obtain the car with the color 'black', model 'batmobile' and the owner's firstname 'Bruce' (oops... spoiler ;) )
I tried to do something like that but it won't work :
List<Car> cars = session.createCriteria(Car.class)
.add(Restrictions.eq("color", "black"))
.add(Restrictions.eq("id.model", "batmobile"))
.createAlias("id.owner", "o")
.add(Restrictions.eq("o.firstname", "Bruce"))
.list();
Result :
Hibernate: select this_.model as model1_0_0_, this_.owner_id as owner_id3_0_0_, this_.color as color2_0_0_ from Car this_ where this_.color=? and this_.model=? and o1_.firstname=?
ERROR: Unknown column 'o1_.firstname' in 'where clause'
What is the right way to obtain what I want ?
update
I tried in hql :
String hql = "FROM Car as car where car.color = :color and car.id.model = :model and car.id.owner.firstname = :firstname";
Query query = em.createQuery(hql);
query.setParameter("color", "black");
query.setParameter("model", "batmobile");
query.setParameter("firstname", "Bruce");
List<Car> cars = query.getResultList();
It works but is there a way to do this with criteria ?
You forgot to add the #Column annotation on top of the firstname and lastname fields (and the color field in Car). In hibernate if a field is not annotated, it doesn't recognize it as a database field. This page should give you a good idea about how to set up your model objects.
NOTE: You can have the column annotation over the getters and be fine, but you didn't show the getters. Either place is fine.
Look at what HQL is spitting back out, specifically the statement (formated for easier reading):
select
this_.model as model1_0_0_,
this_.owner_id as owner_id3_0_0_,
this_.color as color2_0_0_
from Car this_
where
this_.color=?
and this_.model=?
and o1_.firstname=?
It looks like hibernate is translating the field "id.owner" to "o" as your alias told it to to, but for some reason it's not writing down that "id.owner=o" as intended. You may want to do some research into why it may be doing that.
As per https://hibernate.atlassian.net/browse/HHH-4591 there is a workaround.
You have to copy the needed relation-property of the #EmbeddedId (owner in this case) to the main entity (Car in this case) with insertable = false, updatable = false as follows
#Entity
public class Car {
#EmbeddedId
private Id id = new Id();
private String color;
#ManyToOne
#JoinColumn(name = "column_name", insertable = false, updatable = false)
private Owner owner;
#Embeddable
public static class Id implements Serializable {
private static final long serialVersionUID = -8141132005371636607L;
#ManyToOne
private Owner owner;
private String model;
// getters and setters...
// equals and hashcode methods
}
// getters and setters...
}
Then just create directly the alias instead of using the composite id property
List<Car> cars = session.createCriteria(Car.class)
.add(Restrictions.eq("color", "black"))
.add(Restrictions.eq("id.model", "batmobile"))
.createAlias("owner", "o")
.add(Restrictions.eq("o.firstname", "Bruce"))
.list();
I have an Evaluation entity that has an associated list of EvaluationEvaluator. I need to explicitly create that entity because it required an extra column "STATUS". Before I continue evaluation. I do: evaluation.setEvaluationEvaluator(listEvaluator) where listEvaluator is a list of EvaluationEvaluator type. Then persist(evaluation). When I run this, it does not throw any kind of exception. But in the database, it inserts in the Evaluation table, and not inserted into the EvaluationEvaluator table.
Below my Evaluation entity.
#Entity
public class Evaluation implements Serializable{
#Id
#GeneratedValue
private Long id;
//MORE FIELDS
#OneToMany(mappedBy="evaluation")
private List<EvaluationEvaluator> evaluators;
//CONSTRUCTORS
//GETTER AND SETTERS
}
This is my EvalutionEvaluator Entity:
#Entity
#Table(name= "EVALUATION_EVALUATOR")
#IdClass(EvaluationEvaluatorId.class)
public class EvaluationEvaluator implements Serializable{
#Id
#Column(name="EMPLOYEE_ID", insertable=false , updatable=false)
private Long EmployeeID;
#Id
#Column(name="EVALUATION_ID", insertable=false, updatable=false)
private Long EvaluationID;
#ManyToOne
#JoinColumn(name"EMPLOYEE_ID")
private Employee employee;
#ManyToOne
#JoinColumn(name"EVALUATION_ID")
private Evaluation evaluation;
#NotNull
private String status;
//CONSTRUCTORS
//GETTER AND SETTERS
}
This is my EvaluationEvaluatorId class
public class EvaluationEvaluatorId implements Serializable{
private Long employeeID;
private Long evaluationID;
//CONSTRUCTOR
//GETTER AND SETTERS
}
And finally, this is my EvaluationBean class
#Stateful
#Named
#LocalBean
#ConversationScoped
public class EvaluationBean {
#PersistentContext(type= PersistenceContextType.EXTENDED)
private EntityManager em;
#Inject
Conversation conversation;
private Evaluation evaluation;
//IN MY WEBPAGE I IMPLEMENT PRIMEFACES PICKLIST AND IT REQUIRE DUALIST TO HANDLE
private DualListModel<Employe> evaluators;
private EvaluationEvaluator evaluationEvaluator;
private List<EvaluationEvaluator> listEvaluators;
#Inject
private EmployeeList employeeList;
//GETTER AND SETTERS
public String begin(){
if (conversation.isTransient()){
converstaion.begin();
}
evaluationEvaluator = new EvaluationEvaluator();
listEvaluators = new ArrayList<EvaluationEvaluator>();
evaluation = new Evaluation();
List<Employee> source = employeeList.findAll();
target = new ArrayList<Employee>();
evaluators = new DualListModel<Employee>(source, target);
return "/evalution/evaluationAsig.xhtml"
}
public String save(){
Iterator<Employee> iterator = evaluators.getTarget().iterator();
while (iterator.hasNext()){
EvaluationEvaluator ev = new EvaluationEvaluator();
ev.setEmployee(iterator.next());
listEvaluators.add(ev);
}
evalution.setEvaluationEvaluators(listEvaluators);
if(evaluation.getId()==null){
em.persist(evalution);
} else{
em.merge(evalution);
}
if(!conversation.isTransient()){
convesation.end();
}
return "/evalution/evaluationsAsig.xhtml"
}
}
When I debug my application,apparently everything is correct, but I mentioned above, doesn't persist in EvaluationEvaluator table.
Your #OneToMany association is missing cascading configuration.
Add cascade = CascadeType.ALL or cascade = {CascadeType.PERSIST, CascadeType.MERGE} to the #OneToMany annotation. JPA assumes no cascading by default so you would need to persist each EvaluationEvaluator by yourself explicitely otherwise.
UPDATE
There is another thing wrong with the code - the Ids of EvaluationEvaluators are never assigned. You have a complex key made of two Long columns. Both are marked not insertable nor updatable which tells to JPA that the id is going to be somehow generated on database level and it should not care about it. There is however no sequence configured explicitely in your entity (although it is not necessarily required) and also from your comment:
I did what you recommended but it throws the following exception. "A different object with same identifier was already associated with the session"
I assume that this is not the case and both id column values default to null or zero and are same for all EvaluationEvaluators you are trying to persist. If you'd like the database to generate the id for you automatically use #GeneratedValue - Configure JPA to let PostgreSQL generate the primary key value - here you can find explanation how to do this (the database part is database dependent, this is for PostgreSQL). The most common use case however, is to configure the sequence but let hibernate pick the next value, instructions here - Hibernate sequence on oracle, #GeneratedValue(strategy = GenerationType.AUTO)
I have two classes as following,
Human.java
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Human implements Serializable {
private long id;
private String name;
....
}
Student.java
#Entity
#DynamicUpdate
public class Student extends MyFactories {
private List<Know> KnowList;
#OneToMany(fetch = FetchType.LAZY)
public List<Know> getKnowlist() {
return knowlist;
}
public void setKnowlist(List<Know> KnowList) {
return Knowlist;
}
}
Know.java
#Entity
public class Know implements Serializable {
private long id;
private Human hu;
private Student st;
....
#ManyToOne
public Person getHu() {
return hu;
}
#ManyToOne
public Client getSt() {
return st;
}
.... setters .....
}
Code
Know kw = new Know();
kw.setSt(studentObject);
kw.setHu(humanObject);
session.save(kw);
tx.commit();
I am able to insert into Know table but hibernate does not insert any record to student_know table which it has created.
I have found this answer but it says I need to use that method if I always want to retrieve all the records. Which I do not (at times, I may just need to retrieve the student class not list of its know)
System.out.println(this.student.getKnowList().size());
When I try to access the list it runs into following exception.
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.myproject.Student.knowList, could not initialize proxy - no Session
for select case change that #OneToMany(fetch = FetchType.LAZY) to #OneToMany(fetch = FetchType.EAGER) so you can get data inside it's list.
and for the insert i need your clarification about where is your relation or getter setter of the private Factory fac;?
you should have at least something like this :
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "YOUR_FACTORY_ID_COLUMN")
private Factory fac;
public Factory getFac(){
return fac;
}
public void setFac(Factory fac){
this.fac=fac;
}
and did factory have any id?
You need to use session.Update(studentObject) as well, to insert a row into student_know table.
Please also be aware that access to a lazy association outside of the context of an open Hibernate session will result in an exception. Link