I'm having a problem implementing a bi-directional parent/child relationship using hibernate 3. The parent, in this case is of the class ReportCriteria. The child is of class PkVisit. I've pasted my hibernate configuration files as well as the underlying java objects below.
ReportCriteria configuration:
<hibernate-mapping package="org.fstrf.masterpk.domain">
<class name="ReportCriteriaBean" table="masterPkReportCriteria">
<id name="id" column="id">
<generator class="org.hibernate.id.IncrementGenerator" />
</id>
<bag name="pkVisits" table="masterPkWeeks" cascade="all-delete-orphan" inverse="true">
<key column="runId"/>
<one-to-many class="PkVisit"/>
</bag>
</class>
</hibernate-mapping>
ReportCriteria bean:
public class ReportCriteriaBean {
private Integer id;
private List<PkVisit> pkVisits = LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(PkVisit.class));
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<PkVisit> getPkVisits() {
return pkVisits;
}
public void setPkVisits(List<PkVisit> pkVisits) {
this.pkVisits = pkVisits;
}
}
PkVisit Configuration:
<hibernate-mapping package="org.fstrf.masterpk.domain">
<class name="PkVisit" table="masterPkWeeks">
<id name="id" column="id">
<generator class="org.hibernate.id.IncrementGenerator" />
</id>
<many-to-one name="reportCriteriaBean" class="ReportCriteriaBean" column="runid" not-null="true" />
<property name="week" column="week" />
</class>
</hibernate-mapping>
PkVisit Bean:
public class PkVisit {
private Integer id;
private ReportCriteriaBean reportCriteriaBean;
private Integer week;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public ReportCriteriaBean getReportCriteriaBean() {
return reportCriteriaBean;
}
public void setReportCriteriaBean(ReportCriteriaBean reportCriteriaBean) {
this.reportCriteriaBean = reportCriteriaBean;
}
public Integer getWeek() {
return week;
}
public void setWeek(Integer week) {
this.week = week;
}
}
The problem occurs when I try to save an instance of ReportCriteria, which, due to the cascade should also save any child PkVisits as well. However, when the save is called using
hibernateTemplate.saveOrUpdate(reportCriteria);
The following error is generated:
org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value: org.fstrf.masterpk.domain.PkVisit.reportCriteriaBean; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: org.fstrf.masterpk.domain.PkVisit.reportCriteriaBean
When I save a report criteria that contains no PkVisits then everything works as I would expect, but as soon as any elements are in the pkVisits list of the ReportCriteria bean the errors occurs.
SOLUTION EDIT:
My problem was that I was never explicitly setting the parent (ReportCriteriaBean) in the children (PkVisits). I remedied the problem by editing my PkVisits setter in the following way:
public void setPkVisits(List<PkVisit> pkVisits) {
this.pkVisits = pkVisits;
for(PkVisit visit : pkVisits){
visit.setReportCriteriaBean(this);
}
}
It appears that you are not creating the bidirectional link in java properly. I'd recommend creating an add method on ReportCriteriaBean; something to the effect of:
public boolean add(PkVisit pkVisit) {
boolean added = false;
added = getPkVisits().add(pkVisit);
if (added) {
pkVisit.setReportCriteriaBean(this);
}
return added;
}
The error indicates that you cannot save a PkVisit if its ReportCriteriaBean is null. The above code, i think, is your missing link. If you go this route, you just add the PkVisit to the ReportCriteriaBean before persisting the report criteria and all should be well.
Also, here's a link to the hibernate documentation on this subject, section 21.2
Check if the PkVisit is generated ok, prior to the saveOrUpdate() call.
Then, you may need to eager fetch reportCriteriaBean/pkVisits where you have the hibernate session, prior to accessing them where you don't have hibernate session:
Hibernate.initialize(reportCriteriaBean.getPkVisits());
Related
Supposing that we create 2 tables with below SQL :
create table Supplier (id int, name VARCHAR, count int);
create table Product (id int, name VARCHAR, description VARCHAR, price double, supplierId int);
Models:
public class Supplier {
private int id;
private String name;
private int count;
public int getId(){ return id;}
public void setId(int id){ this.id = id; }
public String getName(){ return name;}
public void setName(String name){ this.name = name;}
public int getCount() { return count;}
public void setCount(int count) { this.count = count;}
}
AND
public class Product {
private int id;
private String name;
private String description;
private Double price;
private Supplier supplier;
public int getId() { return id;}
public void setId(int id) { this.id = id; }
public String getName() { return name;}
public void setName(String name) { this.name = name;}
public String getDescription() { return description;}
public void setDescription(String description) { this.description = description; }
public Double getPrice() {return price;}
public void setPrice(Double price) { this.price = price;}
#OneToOne(targetEntity=ProductAssignment.class, mappedBy = "supplierId", fetch = FetchType.LAZY)
public Supplier getSupplier() { return supplier;}
public void setSupplier(Supplier supplier) { this.supplier = supplier; }
}
If I want to select all products order by count in supplier I can use the below code :
Criteria crit = session.createCriteria(Product.class);
Criteria critSupplier = crit.createCriteria("supplier");
critSupplier.addOrder(Order.desc("count"));
But now, I want to select all suppliers order by price in Product table.
if I want to use MySQL, the below is the script:
select * from supplier s inner join product p ON s.id = p.supplierId order by p.price
Now I want to transfer this SQL into Hibernate Criteria query in java code?
Please help me in this case?
Here you have a bidirectional relationship between two models: Supplier and Product. It is a bidirectional relationship since you want both the models to be aware of each other, and recollect each other information, based on the link that joins them (supplierId). The relationship is also a one(Supplier)-toMany(Products)
So, first off, you are missing the fact that also Supplier must be aware of the existence of the relationship. You have to express this "awareness" by modifying the Supplier model and add to it the list products:
public class Supplier implements Serializable{
private int id;
private String name;
private int count;
private List<Product> products;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
#Override
public String toString() {
return "Supplier{" + "name=" + name + '}';
}
The second step is to communicate the ORM(in your case hibernate) the relationship between your two models. Online you can find plenty of documentation that explains this subtle "step" of hibernate. in your case, something like this should do.
Hibernate mapping of Supplier:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.xxx.stackoverflowdb.model.Supplier" table="Supplier">
<id column="id" name="id" type="int">
<generator class="assigned"/>
</id>
<property column="name" name="name" type="string"/>
<property column="count" name="count" type="int"/>
<bag name="products" table="product" inverse="true" lazy="false" fetch="select">
<key>
<column name="id"/>
</key>
<one-to-many class="com.xxx.stackoverflowdb.model.Product"/>
</bag>
</class>
</hibernate-mapping>
Hibernate mapping of Product:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.xxx.stackoverflowdb.model.Product" table="PRODUCT">
<id column="id" name="id" type="int">
<generator class="assigned"/>
</id>
<property column="name" name="name" type="string"/>
<property column="description" name="description" type="string"/>
<property column="price" name="price" type="double"/>
<many-to-one name="supplierId" class="com.xxx.stackoverflowdb.model.Supplier" column="supplierId" insert="false" update="false" lazy="false"/>
</class>
</hibernate-mapping>
As you can see, both mapping files declare the relationship. With this set, you can write the Criteria and have it do the job. Since it now hibernate knows about the relationship, it can help you. I've created a simple tester class that demonstrates it:
public class Tester {
public static void main(String[] args) {
//gets a session, assuming your cg file is in a folder called hibernate_dispatcher
//under classpath
SessionFactory sessionFactory = new Configuration().configure("/hibernate_dispatcher/hibernate.cfg.xml")
.buildSessionFactory();
Session session = sessionFactory.openSession();
//gets a session, assuming your cg file is in a folder called hibernate_dispatcher
//under classpath
//YOUR own query --> gets all products order by count in supplier
Criteria criteria1 = session.createCriteria(Product.class);
criteria1.createAlias("supplierId", "supp");
criteria1.addOrder(Order.desc("supp.count"));
for(Object p:criteria1.list()){
Product nthP=(Product)p;
System.out.println(nthP);
}
//YOUR own query --> gets all products order by count in supplier
//the query you've asked --> gets all products order by price in Product
Criteria criteria2 = session.createCriteria(Supplier.class);
criteria2.createAlias("products", "prod");
criteria2.addOrder(Order.desc("prod.price"));
for(Object s:criteria2.list()){
Supplier nthS=(Supplier)s;
System.out.println(nthS);
}
//the query you've asked --> gets all products order by price in Product
}
}
This question already has answers here:
Hibernate-sequence doesn't exist
(17 answers)
Closed 5 years ago.
I am developing a very basic hibernate application and am stuck with the error:
ERROR: ORA-02289: sequence does not exist.
Attached are the related files. I see this question already been asked in stack overflow but none of them could solve the issue. I have created the sequence school_seq already in Oracle DB.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibEx">
<class name="School" table="school">
<id name="id" column="ID" type="int">
<generator class="sequence">
<param name="sequence">SCHOOL_SEQ</param>
</generator>
</id>
<property name="name" column="NAME"></property>
<property name="subject" column="SUBJECT"></property>
<property name="marks" column="MARKS"></property>
</class>
</hibernate-mapping>
POJO CLASS
package hibEx;
public class School {
private String name;
private String subject;
private int marks;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
First i have created sequence like the below:
CREATE SEQUENCE school_seq
START WITH 411
INCREMENT BY 1;
As i am facing this issue,i have tried multiple practices based on the comments in the group
and later altered the table like the below:
alter sequence school_seq
MINVALUE 411
MAXVALUE 1000
NOCYCLE
CACHE 20
NOORDER
thanks for your support in clearing this problem..On further research i found a comment from Li Ying in the link click here .
It says In Hibernate 5, the param name for the sequence has been changed to <param name="sequence_name">xxxxxx_seq</param> from <param name="sequence">xxxxxx_seq</param>
Make sure your sequence was created in the same schema as the table. Connect with the owner of the SCHOOL table and query these data dictionary views to make sure that the same user owns the table and the sequence.
SELECT
s.sequence_name,
s.sequence_owner
FROM
all_sequences s
WHERE
s.sequence_name = 'SCHOOL_SEQ';
and
SELECT
t.table_name,
t.owner
FROM
all_tables t
WHERE
t.table_name = 'SCHOOL';
My Address Class:
public class Address implements java.io.Serializable {
private String addressId;
private String customerId;
public Address() {
}
public Address(String addressId) {
this.addressId = addressId;
}
public Address(String addressId, String customerId) {
this.addressId = addressId;
this.customerId = customerId;
public String getAddressId() {
return this.addressId;
}
public void setAddressId(String addressId) {
this.addressId = addressId;
}
public String getCustomerId() {
return this.customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
My hbm.xml file:
<class name="Address" table="Address">
<id name="addressId" column="address_id" type="java.lang.String">
<generator class="assigned" />
</id>
<property name="customerId" column="customer_id" type="java.lang.String" />
</class>
I am getting following error
org.hibernate.PropertyNotFoundException: Could not find a getter for customerId in class Address
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:282)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:275)
at org.hibernate.mapping.Property.getGetter(Property.java:272)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:247)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:125)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:56)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:302)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434)
Hibernate could be a bit tricky with capitalization.
Try CustomerId as a property name, and all should be fine. Hibernate expects a getcustomerId method if you name the property customerID
This could happen if you do not set the default attribute in hibernate.hbm.xml file but you have a default value specified for the column in the database.
If you have web aplication in eclipse check that you have same output folder in the java build path and same source folder in Deployment Assembly.
Sometimes you have to put your aliases into escaped quotes (if you use resulttransformer that will inject aliased values into instances of Class via property methods or fields):
session
.createNativeQuery("SELECT something AS /"someThing/"")
.setResultTransformer(Transformers.aliasToBean(MyDao.class))
.getResultList();
In my case. I found there were duplicate classes in my war and jar.Like Jigar Joshi said.
Why this happend? I move some entity to other project that package into a jar file . And I re-deploy my project by war, Tomcat didn't delete the entity class that I remove, the entity class still in the old place and those duplicate with my jar files.
So I delete the duplicate classes
I have a Parent entity that refers a Child entity as a value in a map. The key in the map is an enum (see below for straightforward code). Unfortunately using #AuditJoinTable with a table name doesn't create the expected "parent_children_aud" table.
Is auditing for map references supported? Or is there something that I'm doing wrong?
Using Hibernate 3.6.0.
Parent class:
#Audited
public class Parent {
private Long id;
private Integer version;
private Map<MyEnum, Child> mappedChildren;
protected Parent() {}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
#AuditJoinTable(name = "parent_children_aud")
public Map<MyEnum, Child> getMappedChildren() {
return this.mappedChildren;
}
public void setMappedChildren(Map<MyEnum, TemplateStage> mappedChildren) {
this.mappedChildren = mappedChildren;
}
}
Child class:
#Audited
public class Child {
private Long id;
protected Child() {}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
MyEnum:
public enum MyEnum { AAA, BBB, CCC; }
hbm.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
-//Hibernate/Hibernate Mapping DTD 3.0//EN
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd>
<hibernate-mapping>
<class name="Parent" table="parents">
<cache usage="read-write"/>
<id name="id" column="id">
<generator class="native"/>
</id>
<version name="version" unsaved-value="negative"/>
<map name="mappedChildren" cascade="all-delete-orphan" lazy="true">
<cache usage="read-write"/>
<key column="parent_id"/>
<map-key type="MyEnum"/>
<one-to-many class="Child"/>
</map>
</class>
<class name="Child" table="children">
<cache usage="read-write"/>
<id name="id">
<generator class="native"/>
</id>
<version name="version" unsaved-value="negative"/>
</class>
</hibernate-mapping>
I have 2 mappings like this:
<hibernate-mapping>
<class name="A" table="A">
<id name="code" column="aCode" type="integer">
<generator class="assigned"/>
</id>
<property name="info" type="integer"/>
<set name="Bs" lazy="false">
<key>
<column name="aCode" not-null="true"/>
</key>
<one-to-many class="B"/>
</set>
</class>
<class name="B" table="B">
<id name="code" column="bCode" type="integer">
<generator class="assigned"/>
</id>
<many-to-one name="a"/>
</class>
</hibernate-mapping>
These are the classes:
public class A {
private int code;
private int info;
private Set<B> bs = new HashSet<B>(0);
public A() {};
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public int getInfo() { return info; }
public void setInfo(int info) { this.info = info; }
public Set<B> getBs() { return bs; }
public void setBs(Set<B> bs) { this.bs = bs; }
}
public class B {
private int code;
private A a;
public B() {};
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public A getA() { return a; }
public void setA(A a) { this.a = a; }
}
I'm in a scenario where I have to deal with a long transition and do the following:
// Persistence Layer
Session session = factory.getCurrentSession();
session.beginTransaction();
A a1 = new A(); // Create transient object
a1.setCode(1);
a1.setInfo(10);
session.save(a1); // Persist it
// Something happening in another layer (see below)
// Continuing with the transaction
Object b = ... // Recover object
session.save(b); // Persist it using transient a2 object as a link but don't change/update its data
System.out.println(b.getA().getInfo()); // Returns 0 not 10;
session.commit();
This happens in another layer (don't have access to the session here):
// * Begin in another layer of the application *
A a2 = new A(); // Create another transient object same *code* as before
a2.setCode(1);
B b = new B(); // Create another transient object
b.setCode(1);
b.set(a2);
// * End and send the b Object to the persistence layer *
Is there any way load/get the persistent child object before saving parent one or is there other way to save the child object without change the info and flush it all? I'm not using JPA. Sorry if I'm terrible wrong.
Thank you.
Currently state of the new child is not saved into the database since your relationship doesn't have cascading, so wrong state of the child shouldn't be a big problem.
However, if you want to have consistent state of the entities in memory, you can use merge() instead of save(), without cascading it should work exactly as desired:
b = session.merge(b); // Persist it using transient a2 object as a link but don't change/update its data
System.out.println(b.getA().getInfo()); // Should return 10
See also:
Hibernate: will merge work with many-to-one object transtively?
I think what you want to do is:
A a2 = (A)session.get(A.class, 1);