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!
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
}
}
I am new to Hibernate (implementing since yesterday) and i succesfully created a method, that transfers my Customer Objects to the Database.
After i quit my application and start it again and create a new session (in an other method) based on my hibernate.cfg.xml file with this setting:
<property name="hibernate.hbm2ddl.auto">create</property>
It leads to that point, that all relevant tables, created with Hibernate are being deleted.
So maybe that is a comprehension question, but i think "transparent persistence by hibernate" means also, that my POJO's are persistent beyond the runtime of my application!?
So i read several topics on Stackoverflow and tried it with this setting:
<property name="hibernate.hbm2ddl.auto">update</property>
But this leads to SQL errors:
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
Of course i don't want have duplicates, so i suppose that hibernate doesn't send a SQL Statement referring to an existing object.
It sends a Statement like this:
UPDATE `customer` SET `id`=1,`birthday`='1990-10-05 00:00:00',`forename`='TestCustomer',`gender`='F',`generatedProfitsLastYear`='0',`generatedProfitsTotal`='0',`surename`='A',`gcid`='1'
But i need the same statement, with a
Where `id`=1
at the end.
So basically what i want is, that hibernate doesn't drop all the tables and creates it again when i restart my application and create a new session based on the configuration file. So after i open a new session, i can transfer the Customer Objects stored in the database to POJOs.
Did i understand the concept of hibernate incorrectly or am i making a typical beginners mistake?
Below you will find my Customer Class:
#Entity
#Table(name="CUSTOMER")
public class Customer {
private int id;
private String forename;
private String surname;
private char gender;
private Date birthday;
private double generatedProfitsTotal;
private double generatedProfitsLastYear;
private CustomerGroup assignedTo;
public Customer(int id, String forename, String surname, char gender,
Date birthday) {
super();
this.id = id;
this.forename = forename;
this.surname = surname;
this.gender = gender;
this.birthday = birthday;
}
#Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "forename")
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
#Column(name = "surename")
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Column(name = "gender")
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
#Column(name = "birthday")
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
#Column(name = "generatedProfitsTotal")
public double getGeneratedProfitsTotal() {
return generatedProfitsTotal;
}
public void setGeneratedProfitsTotal(double generatedProfitsTotal) {
this.generatedProfitsTotal = generatedProfitsTotal;
}
#Column(name = "generatedProfitsLastYear")
public double getGeneratedProfitsLastYear() {
return generatedProfitsLastYear;
}
public void setGeneratedProfitsLastYear(double generatedProfitsLastYear) {
this.generatedProfitsLastYear = generatedProfitsLastYear;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="gcid", nullable=true, insertable=true, updatable=true)
public CustomerGroup getAssignedTo() {
return assignedTo;
}
public void setAssignedTo(CustomerGroup assignedTo) {
this.assignedTo = assignedTo;
}
}
my hibernate config file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/hibernatetesting</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="studyproject.Customer"/>
<mapping class="studyproject.CustomerGroup"/>
<mapping class="studyproject.BonusPackage"/>
</session-factory>
</hibernate-configuration>
Thanks
try session.saveOrUpdate() method where you have used session.save() it will prevent your database from dropping while fetching data use it with hbm2ddl.auto update. it worked for me. hope it helps.
What did you do where the 'duplicate error' occurs? Now I have the hibernate.hbm2ddl.auto configured as yours, but it's okay saving or updating entity in my local.
I'm developing an application using Hibernate, Spring and GWT in Java. I used reverse engineering under Hibernate (JBoss Developer Studio used) to obtain POJOs and configuration files from an existing MySQL database. It's very simple database with only two entities: Country and Citizen. They have OneToMany relationship between.
Here is the code:
app entry point:
...
Country country = new Country();
country.setName("NameOfCountry"+i);
country.setPopulation(10000);
Citizen ctz = new Citizen();
ctz.setName("John");
ctz.setSurname("Smith");
ctz.setCountry(country);
country.getCitizens().add(ctz);
service.saveCitizen(ctz, new AsyncCallback<Boolean>(){
#Override
public void onFailure(Throwable caught) {
System.out.println("Problem saving citizen");
}
#Override
public void onSuccess(Boolean result) {
System.out.println("Citizen successfully saved");
}
});
service.saveCountry(country, new AsyncCallback<Boolean>(){
#Override
public void onFailure(Throwable caught) {
System.out.println("Problem saving country");
}
#Override
public void onSuccess(Boolean result) {
System.out.println("Country successfully saved");
}
});
...
-- service provides simple GWT-RPC call to server
Service on server:
#Service("componentService")
public class ComponentServiceImpl implements ComponentService{
#Autowired
private CountryDAO daoCnt;
#Autowired
private CitizenDAO daoCtz;
#Transactional(readOnly=false)
#Override
public boolean saveCitizen(Citizen citizen) {
daoCtz.saveOrUpdate(citizen);
return true;
}
#Transactional(readOnly=false)
#Override
public boolean saveCountry(Country country) {
daoCnt.saveOrUpdate(country);
return true;
}
}
Now SpringDAOs:
CitizenDAO:
#Repository
public class CitizenDAO {
...
public void saveOrUpdate(Citizen citizen){
sessionFactory.getCurrentSession().saveOrUpdate(citizen);
}
...
CountryDAO:
#Repository
public class CountryDAO {
...
public void saveOrUpdate(Country country){
sessionFactory.getCurrentSession().saveOrUpdate(country);
}
...
Finally
Citizen.hbm.xml:
<hibernate-mapping>
<class name="sk.jakub.mod.shared.model.Citizen" table="citizen" catalog="modeldb">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<many-to-one name="country" class="sk.jakub.mod.shared.model.Country" fetch="select">
<column name="Country_id" not-null="true" />
</many-to-one>
<property name="name" type="string">
<column name="name" length="45" not-null="true" />
</property>
<property name="surname" type="string">
<column name="surname" length="45" not-null="true" />
</property>
</class>
</hibernate-mapping>
Country.hbm.xml:
<hibernate-mapping>
<class name="sk.jakub.mod.shared.model.Country" table="country" catalog="modeldb">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="name" length="45" not-null="true" />
</property>
<property name="population" type="int">
<column name="population" not-null="true" />
</property>
<set name="citizens" table="citizen" inverse="true" lazy="true" fetch="select">
<key>
<column name="Country_id" not-null="true" />
</key>
<one-to-many class="sk.jakub.mod.shared.model.Citizen" />
</set>
</class>
</hibernate-mapping>
I havent listed Citizen.java and Country.java because they are only basic POJOs (if necessary I'll provide them).
When I launch my app and I want to save my data into database I obtain following error:
org.hibernate.PropertyValueException: not-null property references a null or transient value: sk.jakub.mod.shared.model.Citizen.country
I can't figure out where is the problem. I was trying also instead of saveOrUpdate method, persist method. Or also to change the order of saving into database. Nothing seemed to work.
Thank you very much for help :) If needed, I can post more code from my application.
EDIT:
code for Citizen.java:
public class Citizen implements java.io.Serializable {
private static final long serialVersionUID = -3102863479088406293L;
private Integer id;
private Country country;
private String name;
private String surname;
public Citizen() {
}
public Citizen(Country country, String name, String surname) {
this.country = country;
this.name = name;
this.surname = surname;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Stat getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return this.surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
Country.java:
public class Country implements java.io.Serializable {
private static final long serialVersionUID = -4085805854508658303L;
private Integer id;
private String name;
private int population;
private Set<Citizen> citizens = new HashSet<Citizen>();
public Country() {
}
public Country(String name, int population) {
this.name = name;
this.population = population;
}
public Country(String name, int population, Set<Citizen> citizens) {
this.name = name;
this.population = population;
this.citizens = citizens;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return this.population;
}
public void setPopulation(int population) {
this.population = population;
}
public Set<Citizen> getCitizens() {
return this.citizens;
}
public void setCitizens(Set<Citizen> citizens) {
this.citizens = citizens;
}
}
Furthermore, I've checked the database manually and Country is saved but citizen is not.
I am seeing that you are creating a Citizen before you create a country. Also both the service calls should be in same transaction for the whole operation to be atomic. The COUNTRY_ID seems to be a self generated id i believe. So once you create the country you can attach that to a citizen but you call stack shows you are creating a citizen which has a Country object which doesnt have an id. This is just my guess. You can try putting both the calls under same transaction and also try creating a Country and attach that country instance to the Citizen.
Please check if you have implemented the equals, hashcode and compareTo (if applicable) methods properly. I have recently faced this problem and resolved it by proper implemetation of these.
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
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.