StackOverflowError on Hibernate Save - java

I have a Student table with an auto generated id as primary key and one to many mappings to Phone table.
My Phone table has a composite primary key PhonePK with phone number and the foreign key id to the Student table.
If I just do student.setPhones and not do phonepk.setStudent, its complaining about id cannot be null. So I am setting student.setPhones and phonePk.setStudent. But now I am getting a stackoverflow error on toString.
I really don't like setting it on both ways in the first place but don't know how to get around the id cannot be null error. I've been asking lot of people but they could not help. Could someone take a look please?
Student.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
#Entity
#SuppressWarnings("serial")
public class Student implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String fName;
private String lName;
private String mName;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "id")
private Set<Phone> phones;
/**
* #return the fName
*/
public String getfName() {
return fName;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #return the lName
*/
public String getlName() {
return lName;
}
/**
* #return the mName
*/
public String getmName() {
return mName;
}
/**
* #return the phones
*/
public Set<Phone> getPhones() {
return phones;
}
/**
* #param fName
* the fName to set
*/
public void setfName(final String fName) {
this.fName = fName;
}
/**
* #param id
* the id to set
*/
public void setId(final int id) {
this.id = id;
}
/**
* #param lName
* the lName to set
*/
public void setlName(final String lName) {
this.lName = lName;
}
/**
* #param mName
* the mName to set
*/
public void setmName(final String mName) {
this.mName = mName;
}
/**
* #param phones
* the phones to set
*/
public void setPhones(final Set<Phone> phones) {
this.phones = phones;
}
/**
* {#inheritDoc}
*/
#Override
public String toString() {
return String.format("Student [id=%s, fname=%s, lname=%s, mname=%s, phones=%s]",
id,
fName, lName, mName, phones);
}
}
Phone.java
import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
#Entity
#SuppressWarnings("serial")
public class Phone implements Serializable {
#EmbeddedId
private PhonePK PK;
private String color;
/**
* #return the color
*/
public String getColor() {
return color;
}
public PhonePK getPK() {
return PK;
}
/**
* #param color
* the color to set
*/
public void setColor(final String color) {
this.color = color;
}
public void setPK(final PhonePK pK) {
PK = pK;
}
/**
* {#inheritDoc}
*/
#Override
public String toString() {
return String.format("Phone [PK=%s, color=%s]", PK, color);
}
}
PhonePK.java
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Embeddable
#SuppressWarnings({ "serial" })
public class PhonePK implements Serializable {
#ManyToOne
#JoinColumn(name = "id", insertable = false, updatable = false)
private Student student;
private String phoneNumber;
public String getPhoneNumber() {
return phoneNumber;
}
public Student getStudent() {
return student;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setStudent(final Student student) {
this.student = student;
}
/**
* {#inheritDoc}
*/
#Override
public String toString() {
return String.format("PhonePK [student=%s, phoneNumber=%s]", student, phoneNumber);
}
}
Main.java
import java.util.LinkedHashSet;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(final String args[]) {
Configuration configuration = new Configuration();
Transaction transaction = null;
configuration.addAnnotatedClass(Student.class);
configuration.addAnnotatedClass(Phone.class);
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Student student = new Student();
student.setfName("Bob");
student.setlName("Buster");
Set<Phone> phones = new LinkedHashSet<Phone>();
Phone phone = new Phone();
phone.setColor("Black");
PhonePK phonePK = new PhonePK();
phonePK.setPhoneNumber("1111111111");
phonePK.setStudent(student); // Do not do this? But won't work (id cannot be null
error) if
// commented out??
phone.setPK(phonePK);
phones.add(phone);
student.setPhones(phones);
try {
transaction = session.beginTransaction();
System.out.println(student.toString()); // stackoverflow error!
session.save(student);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}

It is happening because of the way you have defined toString() methods
Student's toString() is invoking Phone's toString() which is invoking PhonePK's toString() which in turn is invoking Student's toString()...causing infinite loop.
Let see how it is happening in detailed way
In Student toString() because of phones instance variable in it .it will iterate through each phone and call Phone toString()
public String toString() {
return String.format("Student [id=%s, fname=%s, lname=%s, mname=%s, phones=%s]",
id,
fName, lName, mName, phones);
}
In Phone toString() because of PK instance variable in it .it will invoke PhonePK toString()
public String toString() {
return String.format("Phone [PK=%s, color=%s]", PK, color);
}
In PhonePK toString() because of phoneNumber instance variable in it .it will invoke Phone toString()
public String toString() {
return String.format("PhonePK [student=%s, phoneNumber=%s]", student, phoneNumber);
}

Related

Hibernate many-to-one mapping sets foreign key null

Student has multiple laptops. Student oneToMany Laptop mapping
Student.java
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Student {
#Id
private int id;
private StudentName studentName;
private String email;
#OneToMany(mappedBy = "student")
private List<Laptop> laptops = new ArrayList<Laptop>();
public Student() {
}
public Student(int id, StudentName studentName, String email) {
this.id = id;
this.studentName = studentName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public StudentName getStudentName() {
return studentName;
}
public void setStudentName(StudentName studentName) {
this.studentName = studentName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Laptop> getLaptop() {
return laptops;
}
public void setLaptop(List<Laptop> laptops) {
this.laptops = laptops;
}
#Override
public String toString() {
return "Student [id=" + id + ", studentName=" + studentName + ", email=" + email + "]";
}
}
Laptop.java
package com.practice.hibernateDemo.enity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Laptop {
#Id
private int lid;
private String lName;
#ManyToOne
#JoinColumn(name="student_id", referencedColumnName="id")
private Student student;
public Laptop() {
}
public int getLid() {
return lid;
}
public void setLid(int lid) {
this.lid = lid;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Override
public String toString() {
return "Laptop [id=" + lid + ", lName=" + lName + "]";
}
}
Main class
package com.practice.hibernateDemo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.practice.hibernateDemo.enity.Laptop;
import com.practice.hibernateDemo.enity.Student;
import com.practice.hibernateDemo.enity.StudentName;
public class CreateStudent {
public static void main(String[] args) {
Laptop laptop = new Laptop();
laptop.setLid(100);
laptop.setlName("HP");
Student student = new Student();
student.setId(101);
student.setEmail("test#gmail.com");
student.setStudentName(new StudentName("test1","test2", "test3"));
student.getLaptop().add(laptop);
Configuration con = new Configuration().configure().addAnnotatedClass(Student.class).addAnnotatedClass(Laptop.class);
SessionFactory sf = con.buildSessionFactory();
Session session = sf.getCurrentSession();
Transaction tx = session.beginTransaction();
session.save(laptop);
session.save(student);
tx.commit();
}
}
After saving the object , foreign key in laptop table is setting as null
lid lName student_id
100 HP NULL
Anyone know where I did wrong mapping due to which I am getting foreign key as null
Thanksin advance
The "many" side of a 1:many relationship is always the owning side. If the relationship is bidirectional, then the other side will carry a mappedBy attribute, just like the non-owning side of a bidirectional 1:1 relationship. It is the relationship field on the owning side that is meaningful for conveying the relationship to the persistence layer, and you have failed to set that.
For example,
laptop.setStudent(student);

could not determine type for <DataType> at table: TableX, for columns org.hibernate.mapping.Column(userPrefs)

I searched for this on stack overflow and incorporated the suggestion of putting the annotation over fields or getters but still see the issue so posting.
I have a user table and preference table. Here's the schema
create table userpreferences(
ID bigint auto_increment
user_id bigint not null,
preference_id bigint not null,
preference_value varchar(255),
PRIMARY KEY(ID)
)
;
create table user(
user_id bigint auto_increment,
user_name varchar(255) not null,
primary key(user_id)
)
;
I want to be able to write a method in my user POJO to retrieve all Preferences for that user. Here's what I have.
#Entity
#Table(name="user")
public class User extends KeyedEntity {
private Long user_id;
private String userName;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserPreferences> userPrefs = new HashSet<UserPreferences>();
/**
* #return Returns the userName.
*/
#Column(name="USER_NAME")
public String getUserName() {
return this.userName;
}
/**
* #param userName The userName to set.
*/
public void setUserName(String userName) {
this.userName = userName;
}
#Id #Column(name="user_id") #GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() {
return this.user_id;
}
#Override
public void setId(Long id) {
super.setId(id);
}
/**
* Lazy fetch of the set of application attributes this user has set.
* #return
*/
public Set<UserPreferences> getUserPrefs(){
return new HashSet<UserPreferences>(this.userPrefs);
}
/**
* Setter for the user's attributes.
*
* #param userAttributes
*/
public void setUserPrefs(Set<UserPreferences> userPrefs){
this.userPrefs.clear();
this.userPrefs.addAll(userPrefs);
}
}
Here's my user preference class:
#Entity
#Table(name="userpreferences")
public class UserPreferences extends KeyedEntity implements Externalizable, Cloneable {
private static final int VERSION = 1;
private Long prefId;
private Long userId;
private String prefValue;
#Column(name="PREFERENCE_ID")
public Long getPrefId() {
return prefId;
}
public void setPrefId(Long prefId) {
this.prefId = prefId;
}
#Column(name="USER_ID")
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#Column(name="PREFERENCE_VALUE")
public String getPrefValue() {
return prefValue;
}
public void setPrefValue(String prefValue) {
this.prefValue = prefValue;
}
#Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeShort(VERSION);
out.writeObject(this.prefId);
out.writeObject(this.userId);
out.writeObject(this.prefValue);
}
#Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
short version = in.readShort();
if(version>=0){
this.prefId = in.readLong();
this.userId = in.readLong();
this.prefValue =(String) in.readObject();
}
}
#Id #Column(name="ID")
#GeneratedValue(strategy=GenerationType.AUTO)
#Override
public Long getId() {
return id;
}
public void setId(Long id) {
super.setId(id);
}
}
The error I am getting is this:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: user, for columns: [org.hibernate.mapping.Column(userPrefs)]
There are several issues with your code. I don't know why you have a separate id for User and UserPreference when prefId and userId are the primary keys. You should have a User type property with name as user in UserPreferences instead of Long userId. That is what mappedBy="user" indicate in the User class. Also move the annotation to getter. I changed both your classes to make it work. Here is the updated code.
User.java
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "user")
public class User {
private Long user_id;
private String userName;
private Set<UserPreferences> userPrefs;
/**
* #return Returns the userName.
*/
#Column(name = "USER_NAME")
public String getUserName() {
return this.userName;
}
/**
* #param userName
* The userName to set.
*/
public void setUserName(String userName) {
this.userName = userName;
}
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return this.user_id;
}
public void setId(Long id) {
this.user_id = id;
}
/**
* Lazy fetch of the set of application attributes this user has set.
*
* #return
*/
#OneToMany(mappedBy = "user")
public Set<UserPreferences> getUserPrefs() {
return this.userPrefs;
}
/**
* Setter for the user's attributes.
*
* #param userAttributes
*/
public void setUserPrefs(Set<UserPreferences> userPrefs) {
this.userPrefs = userPrefs;
}
}
Preference.java
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "preference")
public class Preference {
private Long pref_id;
private String prefName;
private Set<UserPreferences> userPrefs;
#Id
#Column(name = "pref_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return pref_id;
}
public void setId(Long id) {
this.pref_id = id;
}
#Column(name = "PREF_NAME")
public String getPrefName() {
return prefName;
}
public void setPrefName(String prefName) {
this.prefName = prefName;
}
#OneToMany(mappedBy = "preference")
public Set<UserPreferences> getUserPrefs() {
return userPrefs;
}
public void setUserPrefs(Set<UserPreferences> userPrefs) {
this.userPrefs = userPrefs;
}
}
UserPreferences.java
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "userpreferences")
public class UserPreferences {
private Long id;
private User user;
private Preference preference;
private String prefValue;
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "PREFERENCE_VALUE")
public String getPrefValue() {
return prefValue;
}
public void setPrefValue(String prefValue) {
this.prefValue = prefValue;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="user_id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="pref_id")
public Preference getPreference() {
return preference;
}
public void setPreference(Preference preference) {
this.preference = preference;
}
#Override
public String toString() {
return this.prefValue;
}
}
I removed writeExternal and readExternal methods for simplicity. And here is the usage in order to get the user preferences.
// creating seession factory object
SessionFactory factory = cfg.buildSessionFactory();
// creating session object
Session session = factory.openSession();
// creating transaction object
Transaction t = session.beginTransaction();
User u1 = new User();
u1.setUserName("Jo");
User u2 = new User();
u2.setUserName("Nick");
Preference p = new Preference();
p.setPrefName("mapping");
UserPreferences up1 = new UserPreferences();
up1.setPreference(p);
up1.setUser(u1);
up1.setPrefValue("ManyToMany");
session.save(up1);
UserPreferences up2 = new UserPreferences();
up2.setPreference(p);
up2.setUser(u2);
up2.setPrefValue("OneToMany");
session.save(up2);
t.commit();// transaction is committed
session.close();
session = factory.openSession();
// creating transaction object
t = session.beginTransaction();
Long u1id = u1.getId();
Long u2id = u2.getId();
System.out.println(u1id + ", " + u2id);
User user = (User) session.get(User.class, u1id);
System.out.println(user.getUserName() + ", " + user.getUserPrefs());
user = (User) session.get(User.class, u2id);
System.out.println(user.getUserName() + ", " + user.getUserPrefs());
t.commit();// transaction is committed
session.close();

Model class is being embedded without specifying #Embeddable annotation to the class

I have been trying hibernate-core-4.3.10.Final.jar to create a dummy project. I have created model class UserDetails which have one Address field which is in fact an embeddable object. In model class I have declared this field with #Embedded annotation but I haven't defined Address class as Embeddable using #Embeddable annotation. Still the object is being embedded in the UserDeatils entity. Is #Embeddable annotation optional?? Is #Embedded annotation sufficient for hibernate to do the mapping accordingly?
Following are the code snippets:-
/** UserDetails Class **/
package com.st.hibernate.models;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
#Entity
#Table(name="USER_DETAILS")
public class UserDetails {
#Id
#Column(name="USER_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="USER_NAME")
#Transient
private String userName;
#Embedded
private Address address;
/**
* #return the address
*/
public Address getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(Address address) {
this.address = address;
}
#Temporal(TemporalType.DATE)
private Date currentDate;
#Lob // Large Objects----> CLob/BLob---->Character/Byte Larger Object
private String description;
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the currentDate
*/
public Date getCurrentDate() {
return currentDate;
}
/**
* #param currentDate the currentDate to set
*/
public void setCurrentDate(Date currentDate) {
this.currentDate = currentDate;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the userName
*/
public String getUserName() {
return userName;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
}
and Address Class:-
package com.st.hibernate.models;
public class Address {
private String pincode;
private String city;
private String state;
/**
* #return the pincode
*/
public String getPincode() {
return pincode;
}
/**
* #param pincode the pincode to set
*/
public void setPincode(String pincode) {
this.pincode = pincode;
}
/**
* #return the city
*/
public String getCity() {
return city;
}
/**
* #param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* #return the state
*/
public String getState() {
return state;
}
/**
* #param state the state to set
*/
public void setState(String state) {
this.state = state;
}
}
Thanks in advance.

Spring-Hibernate, Many to Many relationship query

I have two bean classes Student and Course which has many to many relationship with each other. For eg. one student can register for multiple courses and vice versa. I have used HibernateTemplate to save objects into Oracle DB. Following are Student, Course and StudentDao classes.
Student Class
package com.springhibernate;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="Student")
public class Student {
private int studentId;
private String firstName;
private String lastName;
private Set<Course> courses;
#Id
#Column(name="student_id")
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
#Column(name="first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "Student_Course", joinColumns = #JoinColumn(name = "student_id"), inverseJoinColumns = #JoinColumn(name = "course_id"))
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
StudentDao class
package com.springhibernate;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class StudentDao {
private static Helper helper = new Helper();
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
// method to save student
public void saveStudent(Student s) {
template.save(s);
}
// method to return one employee of given id
public Student getById(int id) {
Student s = (Student) template.get(Student.class, id);
return s;
}
public List<Course> findCourse(){
List<Course> list = template.find("from Course");
return list;
}
}
Course Class
package com.springhibernate;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="Course")
public class Course {
private int courseId;
private String courseName;
private Set<Student> students;
#Id
#Column(name="course_id")
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
#Column(name="course_name")
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
#ManyToMany(cascade=CascadeType.ALL,mappedBy="courses")
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
#Override
public int hashCode() {
// TODO Auto-generated method stub
return this.courseId;
}
#Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
Course temp = (Course) o;
return (this.courseId==temp.courseId);
}
}
I have following two queries
I am able to save data in student_course table successfully. I was wondering if I want to retrieve data from student_course table, how can I do it using HibernateTemplate or is there any other way to do so?
For example, query is like
select course_id from student_course where student_id=1
Please note I want just the course id column not complete row.
If in student_course table I want one more column say course_name (from course table), how can I do that?
You can do it in the following way, but keep in mind that the HibernateTemplate is an old API and you should use for example the EntityManager(Factory).
You can get it via the Peristence class.
hibernateTemplate.execute(new HibernateCallback<List>() {
public String doInHibernate(Session s)
throws HibernateException, SQLException {
SQLQuery sql=s.createSQLQuery("select course_id from student_course where student_id=?");
sql.setParameter(0, adventureId);
sql.addScalar(studentID);
return sql.list();
}
});

How to use both #Embadable and #CollectionOfElements in Entity

Hi could anyone please help me to resolve this problem,I have an entity called a person, And I have taken the person states(Instance variables) has personname as String type,person petnames as Set type ,personphonnumbers as Set type(Phone is a class type embeddable),And I want to take the personAddress here the Address is a class type (Embeddable),The address stats(Instance variables ) I want to override in my person class by using #AttributeOverride annotation and #Embedded ,But If I override #AttributeOverride annotation and #Embedded my all Set properties(petnames as Set,Set) will not work. If do like this below the person class will ask (create entity Id or create subclass),if I am not using Address property remaining thing is working fine.
PersonEntity
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import org.hibernate.annotations.CollectionOfElements;
/**
*
* #author hyva
*/
#Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#CollectionOfElements
#JoinTable(name = "PET", joinColumns = {
#JoinColumn(name = "person_id")})
#Column(name = "petname")
private Set<String> petname12 = new HashSet<String>();
public Set<PhoneNumber> getPhones() {
return Phones;
}
public void setPhones(Set<PhoneNumber> Phones) {
this.Phones = Phones;
}
#CollectionOfElements
#JoinTable(name = "ponenumbers", joinColumns = {
#JoinColumn(name = "person_id")})
private Set<PhoneNumber> Phones = new HashSet<PhoneNumber>();
#Embedded
private Address homeAddress =new Address();
#AttributeOverrides({
#AttributeOverride(name = "street", column =
#Column(name = "street")),
#AttributeOverride(name = "zip", column =
#Column(name = "zip")),
#AttributeOverride(name = "country", column =
#Column(name = "country"))
})
public Long getId() {
return id;
}
public Set<String> getPetname12() {
return petname12;
}
public void setPetname12(Set<String> petname12) {
this.petname12 = petname12;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean addPets(String p) {
return petname12.add(p);
}
public boolean addPhones(PhoneNumber p) {
return Phones.add(p);
}
#Override
public String toString() {
return "Person{" + "id=" + id + ", name=" + name + ", petname12=" + petname12 + '}';
}
}
Address class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts;
import java.io.Serializable;
import javax.persistence.Embeddable;
/**
*
* #author hyva
*/
#Embeddable
public class Address implements Serializable {
private String street;
private String zip;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}

Categories

Resources