Hibernate mapping of two classes to a single row in a table - java

Is it possible to map two classes into single row in a table in Hibernate
I have two classes:
public class Student implements java.io.Serializable {
private int studentId;
private String studentName;
public Student() {
}
public int getStudentId() {
return this.studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return this.studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
and :
public class Address implements java.io.Serializable {
private String street;
private String city;
public Address() {
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
I would like to create a table :
CREATE TABLE "STUDENT"
("STUDENTID" NUMBER(10,0) PRIMARY KEY,
"STUDENTNAME" VARCHAR2(250),
"STREET" VARCHAR2(250),
"CITY" VARCHAR2(250)
)
and map STUDENTID and STUDENTNAME from STUDENT class and STREET and CITY from the ADDRESS class.
Mappings I have done currently is the following:
<hibernate-mapping>
<class name="com.vaannila.student.Address" table="STUDENT">
<id>
<generator class="assigned"/>
</id>
<property name="street" column="SREET" type="string" length="250"/>
<property name="city" column="CITY" type="string" length="250"/>
</class>
</hibernate-mapping>
and :
<hibernate-mapping>
<class name="com.vaannila.student.Student" table="STUDENT">
<id name="studentId" column="STUDENTID" type="int"/>
<property name="studentName" column="STUDENTNAME" type="string" length="250"/>
</class>
</hibernate-mapping>
I am getting error:
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource com/vaannila/student/Address.hbm.xml
Caused by: org.hibernate.MappingException: must specify an identifier type: com.vaannila.student.Address
Please help

This is bad design, from both a Java object and database entity point of view. Look at your address configuration file - I think you can see where it falls apart, evidenced by your attempt to define an id field. Always try and keep in mind what you are trying to model, in this case, Students and Addresses. If those two entities are always going to be one-to-one then go ahead and consolidate the Address and Student classes (as opposed to trying to split them up).
Of course, I think you will find that the relationship is really Many-to-One. And if we are talking college here than its Very-Many-to-One. The examples on Vaanila are structured that way for a reason, I recommend studying them in detail:
http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-many-to-one-1.html

You should be able to do this pretty easily. Here is how using annotations from another question:
Single Table Inheritance WITHOUT Discriminator column
You will have to figure out the translation to XML on your own if that is desired!

yes its possible you can use component tag in xml.

Related

Select and order list by other condition(Criteria inner join hibernate)

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
}
}

ERROR: ORA-02289: sequence does not exist in hibernate [duplicate]

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';

#AttributeOverrides and #Embeddable not working

This is from Hibernate Recipies book at chapter 3 first question when I am trying to run I am getting the following error Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: com.fun.hibernate.auto.idgen.Order column: address (should be mapped with insert="false" update="false")
Here is the code
#Entity
#org.hibernate.annotations.Entity(dynamicInsert=true, dynamicUpdate=true)
#Table(name="ORDERS")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="orderSequence" )
#SequenceGenerator(name="orderSequence",sequenceName="ORDERSEQ")
private Long id;
private Contact weekdayContact;
private Contact holidayContact;
public Order() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Contact getWeekdayContact() {
return weekdayContact;
}
public void setWeekdayContact(Contact weekdayContact) {
this.weekdayContact = weekdayContact;
}
#Embedded
#AttributeOverrides({
#AttributeOverride(name="recipient",column=#Column(name ="HOLIDAY_RECIPIENT")),
#AttributeOverride(name="phone",column=#Column(name ="HOLIDAY_PHONE")),
#AttributeOverride(name="address",column=#Column(name ="HOLIDAY_ADDRESS"))
})
public Contact getHolidayContact() {
return holidayContact;
}
public void setHolidayContact(Contact holidayContact) {
this.holidayContact = holidayContact;
}
}
Embeddable Object
#Embeddable
public class Contact {
private String recipient;
private String phone;
private String address;
public Contact() {
}
#Column(name = "WEEKDAY_RECIPIENT")
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
#Column(name ="WEEKDAY_PHONE")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Column(name ="WEEKDAY_ADDRESS")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Any ideas how to solve this??????????????
Reading the Hibernate Recipes book cited above I could easily reach the exactly point you described on your question.
I couldn't create the same environment that you are working on, so I had to read and interpret what the book says about mapping by annotations and by external configuration files (XML).
By studying your code and the book chapter I think that there are a high probably that you doing some redundancy in the mapping your embedded object, so there is what I think it's the exactly(or close to it) problem:
In the configuration file the book says to create the manual mapping by tags, just like this:
<component name="weekdayContact" class="Contact">
<property name="recipient" type="string" column="WEEKDAY_RECIPIENT" />
<property name="phone" type="string" column="WEEKDAY_PHONE" />
<property name="address" type="string" column="WEEKDAY_ADDRESS" />
</component>
<component name="holidayContact" class="Contact">
<property name="recipient" type="string" column="HOLIDAY_RECIPIENT" />
<property name="phone" type="string" column="HOLIDAY_PHONE" />
<property name="address" type="string" column="HOLIDAY_ADDRESS" />
</component>
Just above this the book also says that you need to create the mapping by annotations:
#Embedded
#AttributeOverrides({
#AttributeOverride(name="recipient",column=#Column(name ="HOLIDAY_RECIPIENT")),
#AttributeOverride(name="phone",column=#Column(name ="HOLIDAY_PHONE")),
#AttributeOverride(name="address",column=#Column(name ="HOLIDAY_ADDRESS"))
})
public Contact getHolidayContact() {
return holidayContact;
}
So, I think that's there only two possible things happening here:
You are mapping the embedded object in the XML file and in the class. In this case you should do it just by one type, preferably by annotations.
I could see that your code differs that the one the book states, and this may be causing the failure. In this case you should read again your whole code and see if there's any differential than the book one, and then correct it to be working just like it's written in the examples.
That's it, good luck!

How to add column automatically in hibernate.hbm.xml and users.java

i have java project i am creating with hibernate using NetBeans ide7.4 till now i have created
users.hbm.xml file and users.java file which based on table in database but now i have added some more column in users table so please tell me how can i update my users.hbm.xml and users.java corresponding my database table when i increase table in database or add some more column in table for doing it i have fallow number of tutorial but still now i am facing problem so please solve my problem
before my users table has only 1 column
id
and my users.java is
package clinic.entity;
// Generated 17 Jan, 2014 4:36:15 PM by Hibernate Tools 3.6.0
public class Users implements java.io.Serializable {
private int id;
public Users() {
}
public Users(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}
and my users.hbm.xml file is
<?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">
<!-- Generated 17 Jan, 2014 4:36:16 PM by Hibernate Tools 3.6.0 -->
<hibernate-mapping>
<class name="clinic.entity.Users" table="users" catalog="clinic_mgmt">
<id name="id" type="int">
<column name="id" />
<generator class="assigned" />
</id>
</class>
</hibernate-mapping>
now i have added 2 more column in table then schema is this
id|name |email
so tell me how to update my both file automatically
It's easier to do things in the opposite direction: update Java first, then generate the database schema with (because the xml file can contain most of the schema).
Now that you've added these columns, you must add field in your java file for each new column, then map them in the xml file.
For instance, if you have a new column email VARCHAR(128), you would add a String field in then java class, then map in with a <property> element in your xml file:
users.java:
private String email;
...
public String getEmail() {
return email;
}
public void setEmail(String newValue) {
email = newValue;
}
users.hbm.xml:
<property column="EMAIL" length="128" name="email"/>
you can use javax.persistence package annotation for that :
#Basic(fetch=FetchType.LAZY)
#Column(name="firstname")
private String firstname;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}

org.hibernate.PropertyNotFoundException: could not find getter for customerId in class Address

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

Categories

Resources