-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Hibernate composite key with foreign key to another table
PostPosted: Wed Jul 03, 2013 11:16 am 
Newbie

Joined: Sat Jun 29, 2013 12:08 pm
Posts: 5
I have a Student table with an auto generated id as primary key and one to many mapping to Phone table.

My Phone table has a composite key PhonePK with phone number and the foreign key id to the Student table as primary keys.

If I do phonePk.setStudent it works but I really don't want to do this. How can I achieve this? If its not achievable, I would like to settle with setting the student id but not the whole student object. How do I do this? Would really appreciate if someone can give an insight on this.

student.java

Code:
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;
    }

}



Phone.java
Code:
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;
    }

}


PhonePK.java
Code:
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;
    }

}


Main.java

Code:
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();
            session.save(student);
            transaction.commit();
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }

    }
}


hibernate.cfg.xml

Code:
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC 
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
  <session-factory> 
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 
    <property name="hibernate.connection.password">cosmo99</property> 
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ops_suite</property> 
    <property name="hibernate.connection.username">cosmo-security</property> 
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
    <property name="hbm2ddl.auto">create</property> 
</session-factory> 
</hibernate-configuration>


Top
 Profile  
 
 Post subject: Re: Hibernate composite key with foreign key to another table
PostPosted: Mon Jul 08, 2013 4:36 am 
Newbie

Joined: Thu May 29, 2008 3:14 am
Posts: 4
even after setting the student, I have the exception saying the id is null. do you know why ? I actually have the association outside the PK within the Phone class itself. does it matter ?


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.