So, you have a one to one with a User and an Address, or a one to many?
I have a little tutorial that maps a one-to-one relationship between an Exam and an ExamDetail. It's a one-to-one.
http://jpa.ezhibernate.com/Javacode/learn.jsp?tutorial=17mappingonetooneassociations
I use annotations, but you just have to find the equivalent xml mapping. With annotations it looks like this:
Code:
@Entity
@Table(name = "exam", schema = "examscam")
public class Exam {
/* @Basic annotation has been
added to all basic fields*/
private int id;
private String shortName;
private ExamDetail detail;
@Id
@GeneratedValue
@Column(name = "id")
public int getId() { return id; }
private void setId(int id) {this.id = id;}
@OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="detail_id")
public ExamDetail getDetail() {return detail; }
public void setDetail(ExamDetail detail) {
this.detail = detail;
}
@Basic
public String getShortName() { return shortName;}
public void setShortName(String shortName) {
this.shortName = shortName;
}
}
Now the detail class:
Code:
@Entity
@Table(name = "exam_detail", schema = "examscam")
public class ExamDetail {
/* @Basic annotation has been
added to all basic fields*/
private int id;
private String fullName;
private int numberOfQuestions;
private int passingPercentage;
private Exam exam;
@Id
@GeneratedValue
@Column(name = "id")
public int getId() {return id;}
private void setId(int id) {this.id = id;}
@OneToOne(cascade=CascadeType.ALL, mappedBy="detail")
public Exam getExam(){return exam;}
public void setExam(Exam exam){this.exam=exam;}
@Basic
public String getFullName() {return fullName;}
public void setFullName(String fullName) {
this.fullName = fullName;
}
@Basic
public int getNumberOfQuestions() {
return numberOfQuestions;
}
public void setNumberOfQuestions(int numberOfQuestions){
this.numberOfQuestions = numberOfQuestions;
}
@Basic
public int getPassingPercentage() {
return passingPercentage;
}
public void setPassingPercentage(int passingPercentage){
this.passingPercentage = passingPercentage;
}
Once that's done, running the code is very natural:
Code:
public static void main(String args[]){
HibernateUtil.recreateDatabase();
Exam exam = new Exam();
exam.setShortName("SCJA");
ExamDetail detail = new ExamDetail();
detail.setFullName("Sun Certified Java Associate");
detail.setPassingPercentage(62);
detail.setNumberOfQuestions(55);
exam.setDetail(detail);
Session session = HibernateUtil.beginTransaction();
//possible due to CascadeType.ALL
session.save(exam);
HibernateUtil.commitTransaction();
}
Here's the tutorial if you want to follow through it.
http://jpa.ezhibernate.com/Javacode/learn.jsp?tutorial=17mappingonetooneassociations
You say its not working. Is there a specific exception you are getting that we can use to narrow down the problem?[/url]