ankit goyal
ankit goyal

Reputation: 1

One To Many Bidirectional Mapping

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 ?

Upvotes: 0

Views: 187

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

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:

Upvotes: 1

Related Questions