-->
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.  [ 16 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: one to many mapping using annotations issues
PostPosted: Wed May 19, 2010 8:26 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
Hi All,

I have two table USER and ADDRESS. A user may have more than one address.
I have two address for one user

I have used the code
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
@JoinColumn(name = "login_id", nullable = false)
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Set<AddressDO> userAddress;

This is working fine for insert operation in session.save(userDo);
But for session.update(userDo); instead of updating the address table it is inserting again.
For delete also the USER table got deleted but not from ADDRESS table

Anybody can give me some tips how to solve this?


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Wed May 19, 2010 9:05 am 
Hibernate Team
Hibernate Team

Joined: Thu Apr 05, 2007 5:52 am
Posts: 1689
Location: Sweden
This is really a question for the Hibernate Users forum.
It would help if you post your full hibernate configuration though and also the code you try to execute within the session.


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Thu May 20, 2010 12:25 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
This is the userDo
Code:
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "USER", uniqueConstraints = { @UniqueConstraint(columnNames = { "user_id" }) })
public class UserDO {
   @Id
   @Column(name = "user_id", columnDefinition = "VARCHAR(255) NOT NULL DEFAULT ''", insertable = true)
   private String userId;

   @Column(name = "password", columnDefinition = "VARCHAR(255) NOT NULL DEFAULT ''", insertable = true)
   private String password;

   @Column(name = "first_name", columnDefinition = "VARCHAR(255) NOT NULL DEFAULT ''", insertable = true)
   private String firstName;

   @Column(name = "last_name", columnDefinition = "VARCHAR(255) NOT NULL DEFAULT ''", insertable = true)
   private String lastName;

      @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
   @JoinColumn(name = "user_id", nullable = false)
   @org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
   private Set<AddressDO> userAddress;   

   public String getUserId() {
      return userId;
   }

   public void setUserId(String userId) {
      this.userId = userId;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   public Set<AddressDO> getUserAdrress() {
      return this.userAddress;
   }

   public void setUserAdrress(Set<AddressDO> userAddress) {
      this.userAddress = userAddress;
   }

}

this is AddressDO
Code:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "ADDRESS",uniqueConstraints = {
      @UniqueConstraint(columnNames={"address_id"})}
)
public class AddressDO {

   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "address_id", insertable = true)
   private long  address_id;      
   
   @Column(name = "city", columnDefinition = "VARCHAR(100) NOT NULL DEFAULT ''", insertable = true)
   private String city;
   
   @Column(name = "state", columnDefinition = "VARCHAR(100) NOT NULL DEFAULT ''", insertable = true)
   private String state;
   
   @Column(name = "zipcode", columnDefinition = "VARCHAR(25) NOT NULL DEFAULT ''", insertable = true)
   private String zipcode;

   public AddressDO() {
   }

   public AddressDO(String state, String street,
         String zipcode) {      
      this.state = state;
      this.street = street;
      this.zipcode = zipcode;
   }

   public long getAddress_id() {
      return address_id;
   }

   public void setAddress_id(long address_id) {
      this.address_id = address_id;
   }

   public String getStreet() {
      return street;
   }

   public void setStreet(String street) {
      this.street = street;
   }

   public String getState() {
      return state;
   }

   public void setState(String state) {
      this.state = state;
   }

   public String getZipcode() {
      return zipcode;
   }

   public void setZipcode(String zipcode) {
      this.zipcode = zipcode;
   }   
   
}

then my functioning class
Code:
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.cognizant.cloudone.dal.dao.intf.UserDAO;
import com.cognizant.cloudone.dal.dbo.UserDO;

public class UserDaoImpl extends BaseDaoImpl implements
      UserDAO {

   public UserDO create(UserDO userDo) {
      return excute(userDo, DataBaseOperationType.create);
   }

   public int delete(UserDO userDo) {
      excute(userDo, DataBaseOperationType.delete);
      return 1;
   }
   
   public UserDO update(UserDO userDo) {
      return excute(userDo, DataBaseOperationType.update);
   }
   
   private UserDO excute(UserDO userDo, DataBaseOperationType operation) {
      Transaction tx = null;
      Session session = getSession();
      try {
         tx = session.beginTransaction();
         switch (operation) {
            case create:
               session.save(userDo);
               break;
            case update:
               session.update(userDo);
               break;
            case delete:
               session.delete(userDo);
               break;
            default:
               break;
         }
         tx.commit();
         return userDo;
      } catch (RuntimeException e) {
         if (tx != null && tx.isActive()) {
            try {
               tx.rollback();
            } catch (HibernateException e1) {
               logger.debug("Error rolling back transaction");
            }
         }
      }
      return null;
   }

}


Last edited by Vasna on Wed May 26, 2010 4:32 am, edited 2 times in total.

Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Mon May 24, 2010 7:04 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
Anybody know how to write the onetomany mapping using annotation for hibernate.
I have also tried with
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "login_id")
@org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Set<AddressDO> userAddress;


Same result


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Mon May 24, 2010 11:37 am 
Regular
Regular

Joined: Tue May 11, 2010 5:50 pm
Posts: 54
Location: Norman, Ok, U.S.A
Try writing like this

Code:
@OneToMany(cascade= CascadeType.ALL, mappedBy="relation field", fetch = FetchType.EAGER)
private Set<AddressDO> userAddress;

on address bean
@ManyToOne
@JoinColumn (name = "relation field", nullable = true/false)
private User user


see if this helps


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Tue May 25, 2010 6:05 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
Same result working for save but, for update new records are inserted to address table instead of update.
During deletion record from user table is only deleted nor from ADDRESS.


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Tue May 25, 2010 11:54 am 
Regular
Regular

Joined: Tue May 11, 2010 5:50 pm
Posts: 54
Location: Norman, Ok, U.S.A
You don't @Unique... on the id if it auto since it will create a new one anyways.
Another thing is that you have defined cascade twice, one with javax.presistance and another with hibernate annotation. Use only one with the properties that are required preferably the javax.presestiance


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Wed May 26, 2010 2:05 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
You mean we can't update a record in a table with auto_increment id?

I have changed the code in UserDO to
Code:
@OneToMany(cascade= CascadeType.ALL, mappedBy="userDO", fetch = FetchType.LAZY)
    private Set<AddressDO> userAddress;


and code added in AddressDO
Code:
@ManyToOne
   @org.hibernate.annotations.Cascade(value = { org.hibernate.annotations.CascadeType.SAVE_UPDATE })
   @JoinColumn(name="user_id")   
   private UserDO userDO;


but it is still working fine for insert and for update new records are inserted to address table instead of update.
During deletion record from user table is only deleted nor from ADDRESS.


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Wed May 26, 2010 11:01 am 
Regular
Regular

Joined: Tue May 11, 2010 5:50 pm
Posts: 54
Location: Norman, Ok, U.S.A
I think what is happening here is that it is some how regenerating a new ID when you are trying to update.

The reason is that may be your are updating the record outside the session and then when you try to update the record, it thinks it is a new record and generates a new key.
You can try this:
load/get the object before updating using the id
make changes
update object


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Wed Jun 02, 2010 1:17 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
While fetching the UserDO it is not fetching the AddressDO which is part of it.

Any helping clues for this?


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Wed Jun 02, 2010 1:22 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
while fetching UserDO it is not fetching the AddressDO which is part of it.

Any help on this?


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Wed Jun 02, 2010 10:55 am 
Regular
Regular

Joined: Tue May 11, 2010 5:50 pm
Posts: 54
Location: Norman, Ok, U.S.A
Try changing the Fetching to EAGER instead of LAZY, see if that works


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Thu Jun 10, 2010 3:21 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
Thanks ivirani,
I have tried with this and it works but the problem now is

I have one record in user table and two records in Address table corresponding to that table.
When I fetched the userDO using the userID it is returning two userDO object with same details.
I think due to two records in address it is fetching twice.

Any idea to resolving this?


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Thu Jun 17, 2010 11:59 am 
Regular
Regular

Joined: Tue May 11, 2010 5:50 pm
Posts: 54
Location: Norman, Ok, U.S.A
Can you add the code you are using to fetch the user?


Top
 Profile  
 
 Post subject: Re: one to many mapping using annotations issues
PostPosted: Fri Jun 18, 2010 12:09 am 
Newbie

Joined: Wed May 19, 2010 6:03 am
Posts: 19
Thanks ivirani for you support I got it resolved using the following code

In user
Code:
    @OneToMany(cascade = {CascadeType.REMOVE}, mappedBy="userDO", fetch = FetchType.LAZY)   
    private Set<AddressDO> userAddress;


and in Address
Code:
    @JoinColumn(name = "user_id")
    @ManyToOne(optional = true)
    @ForeignKey(name = "user_id")
    private UserDO userDO;


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

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.