0

I have the following files in a hibernate project :

Customer.java , Request.java, Client.java and hibernate.cfg.xml as follows :

Customer.java

        @Entity
        @Table(name="customers")
        public class Customer {

            @Id
            @Column(name="cid")
            @GeneratedValue(strategy=GenerationType.AUTO)
        private int cid;
            @Column(name="name")
        private String name;
            @Column(name="phone")
        private long phone;

            @OneToMany(mappedBy="customer")
        private Set<Request> requests;


        public Customer() {
            super();
        }
        public Customer(String name, long phone) {
            super();
            this.name = name;
            this.phone = phone;
        }
        public int getCid() {
            return cid;
        }
        public void setCid(int cid) {
            this.cid = cid;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public long getPhone() {
            return phone;
        }
        public void setPhone(long phone) {
            this.phone = phone;
        }
        public Set<Request> getRequests() {
            return requests;
        }
        public void setRequests(Set<Request> requests) {
            this.requests = requests;
        }
        @Override
        public String toString() {
            return "Customer [cid=" + cid + ", name=" + name + ", phone=" + phone
                    +"]";
        }
        }

Request.java

        @Entity
        @Table(name="requests")
        public class Request {

            @Id
            @Column(name="reqid")
            @GeneratedValue(strategy=GenerationType.AUTO)
        private int reqId;

            @Column(name="reqdate")
        private String reqDate;

            @Column(name="description")
        private String description;
            @Column(name="status")
        private String status;

        @ManyToOne
        @JoinColumn(name="cid",referencedColumnName="cid")
        private Customer customer;

        public Request() {
            super();
        }

        public Request(String reqDate, String description, String status) {
            super();
            this.reqDate = reqDate;
            this.description = description;
            this.status = status;
        }

        public int getReqId() {
            return reqId;
        }

        public void setReqId(int reqId) {
            this.reqId = reqId;
        }

        public String getReqDate() {
            return reqDate;
        }

        public void setReqDate(String reqDate) {
            this.reqDate = reqDate;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public Customer getCustomer() {
            return customer;
        }

        public void setCustomer(Customer customer) {
            this.customer = customer;
        }

        @Override
        public String toString() {
            return "Request [reqId=" + reqId + ", reqDate=" + reqDate
                    + ", description=" + description + ", status=" + status
                    + ", customer=" + customer + "]";
        }
        }

hibernate.cfg.xml

    <?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.url">jdbc:mysql://localhost:3306/ahamdb</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">root</property>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>     

            <mapping class="com.kar.hibernate.Customer" />
    <mapping class="com.kar.hibernate.Request" />
        </session-factory>
    </hibernate-configuration>

Client.java

        public class Client{
        public static void main(String[] args) {
            Transaction tx=null;
            try
            {
            SessionFactory sessionFactory=AHibernateUtil.getSessionFactory();
            Session session=sessionFactory.openSession();
            tx=session.beginTransaction();

            Customer cust=new Customer("bnuj",1111);
            session.save(cust);

        Request req1=new Request("4-1-14", "desc1", "active");
            session.save(req1);

            Request req2=new Request("4-2-14", "desc2", "unactive");
            session.save(req2);

            Set<Request> requests=new HashSet<Request>();
            requests.add(req1);
            requests.add(req2);
            cust.setRequests(requests);

        tx.commit();
        session.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
                if(tx!=null)
                tx.rollback();
            }
        }
        }

The problem is , when i am running the client code , it is producing result as :

    Hibernate: insert into customers (name, phone) values (?, ?)
    Hibernate: insert into requests (cid, description, reqdate, status) values (?, ?, ?, ?)
    Hibernate: insert into requests (cid, description, reqdate, status) values (?, ?, ?, ?)

It is not updating the foreign key column in request table , I am not getting why its is so Could anyone help ?

I want to know whether I am doing it correctly or not , if not, could anyone post the correct solution ?

Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67

1 Answers1

1

The issue comes with inverse mapping. If we declare this: @OneToMany(mappedBy="customer"), namely the mappedBy, we instruct Hibernate:

The other end of relationship will care about persistence.

And it will, well it would, if the other end - the Request, would know about it - would have the Customer properly assigned. So this should fix that:

...
cust.setRequests(requests);
req1.setCustomer(cust);
req2.setCustomer(cust);

Hibernate is now having enough information to properly insert/update the relation

This reading also should help:

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Hi, Thanks for your reply, It is working with : req1.setCustomer(cust); req2.setCustomer(cust); but i want to know what should i do in currrent implementation to make it work with : cust.setRequests(requests); Anyways, thanks for the help – ankit goyal Sep 22 '14 at 17:35
  • I would strongly suggest: use the approach I showed you in my answer. This will generate the most efficient SQL Statements. Any other mapping will cause more complicated handling 1) one special insert of the collection item 2) next update with relation to the parent. Also Updates of the collection will be more complex. In fact - your mapping is the best. Just adjust few lines in the code to set the both sides of the relationship. This is the way... really. Enjoy Hiberante ;) – Radim Köhler Sep 22 '14 at 18:05
  • just adjust few lines in the code to set the both sides of the relationship. Could you tell me this code : – ankit goyal Sep 22 '14 at 19:04
  • Sorry for confusion, but these few lines is content of my answer. I mean, always ALWAYS assign both ends. Put child into parent's collection and assign parent reference to every child. That's it. These line of code will provide Hibernate with enough information - all will be persisted correctly. good luck – Radim Köhler Sep 23 '14 at 04:03
  • Great if that helped anyhow ;) Enjoy Hibernate – Radim Köhler Sep 23 '14 at 17:31