Lets we will use the Collection for that.
1. In this code snip, User has one address
2. In this code snip User has two addresses
}
3. In this code snip User has more than two addresses
In the third case how to manage the records about addresses for that user, now for managing this type of problems we have to use the collection, we do not need to care about how many of the addresses user has. Let’s see there is the same change in the code for that…
We look following example of Object of Entity Type:
public class UserDetails{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long userId;
@Column(name=”USER_NAME”, type=”String”)
private String userName;
@ElementCollection
private Collection<Address> lisOfAddresses = new ArrayList<Address>();
public Collection<Address> getLisOfAddresses() {
return lisOfAddresses;
}
public void setLisOfAddresses(Collection<Address> lisOfAddresses) {
this.lisOfAddresses = lisOfAddresses;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString()
{
return “[User Name: “+userName+”n Office Address: “+lisOfAddresses+”]”;
}
}
@ElementCollection:
Target:
Fields (including property get methods)Defines a collection of instances of a basic type or embeddable class. Must be specified if the collection is to be mapped by means of a collection table.
Address.java
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable //for value object it is not is an entity object. Value object means does not have real meaning for self individually.
public class Address
{
@Column(name=”STREET_NAME”)
private String street;
@Column(name=”CITY_NAME”)
private String city;
@Column(name=”STATE_NAME”)
private String state;
@Column(name=”PIN_CODE”)
private String pincode;
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;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String toString()
{
return ” {Street: “+street+” City: “+city+” State: “+state+” Pincode: “+pincode+” }”;
}
}
hibernate.cfg.xml will be the same as the previous chapter.
HibernateTestDemo.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.sdnext.hibernate.tutorial.dto.Address;
import com.sdnext.hibernate.tutorial.dto.UserDetails;
public class HibernateTestDemo {
/**
* @param args
*/
public static void main(String[] args)
{
UserDetails user = new UserDetails();//Create user object
user.setUserName(“Dinesh Rajput”); //Set user name
Address address1 = new Address(); // create first embedded object address
address1.setStreet(“First Street”);
address1.setCity(“First City”);
address1.setState(“First State”);
address1.setPincode(“First Pin”);
Address address2 = new Address(); // create second embedded object address
address2.setStreet(“Second Street”);
address2.setCity(“Second City”);
address2.setState(“Second State”);
address2.setPincode(“Second Pin”);
//adding addresses object to the list of address
user.getLisOfAddresses().add(address1);
user.getLisOfAddresses().add(address2);
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); //create session factory object
Session session = sessionFactory.openSession(); //create session object from the session factory
session.beginTransaction(); //initialize the transaction object from session
session.save(user); // save the user
session.getTransaction().commit(); //commit the transaction
session.close(); //closing session
}
}
Output:
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate: insert into TBL_USER_DETAILS (USER_NAME) values (?)
Hibernate: insert into TBL_USER_DETAILS_lisOfAddresses (TBL_USER_DETAILS_USER_ID, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)
Hibernate: insert into TBL_USER_DETAILS_lisOfAddresses (TBL_USER_DETAILS_USER_ID, CITY_NAME, PIN_CODE, STATE_NAME, STREET_NAME) values (?, ?, ?, ?, ?)
In the second table first column, TBL_USERS_DETAILS_USER_ID has the user id is foreign key for this table and primary key of the TBL_USER_DETAILS table.
In Next Chapter, you will learn more about the configuration of the collection and adding keys.
<<Previous Chapter 13<< >>Next Chapter15
good
hi dinesh there is a probleme while running above programm or query it shows error @EmbeddedCollection please tell me why it occurs or which type of plugnin i have to use
Hi Aryan,
Please provide error log which error is coming.
Thanks,
Dinesh
Hi Dinesh
I got an error when i run this prog and error is …………
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]
Hi Dinesh
I got same error as mentioned above :
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.Property.isValid(Property.java:185)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:440)
at org.hibernate.mapping.RootClass.validate(RootClass.java:192)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1102)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1287)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at pack.TestDemo.main(TestDemo.java:35)
Please help me out to resolve this
You did problem in mapping.
Nice article!!!
Hi Dinesh, I have the exact same problem and I can't figure out what mistake I am doing in mapping. Can you please elaborate?
HI i faced the same problem org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns:
But i fixed this by adding @OneToMany annotations on addressList field
Hi too got Mapping Exception as others and it got fixed by adding @OneToMany annotations as suggested by asad .Thank you
Thank you it helped me to solve issue
hello Sir,
I wanted to save list of entity in single DB connection.
how can i do ?
tx in advance
In this example, I am using a single connection.