-->
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.  [ 9 posts ] 
Author Message
 Post subject: Collection of 'a' entities in entity a - pri key constraint
PostPosted: Thu Mar 06, 2008 11:16 pm 
Beginner
Beginner

Joined: Wed Mar 05, 2008 10:32 am
Posts: 48
I'm having an issue with creating a set of objects inside that object.

My mapping for the UserEnt class
Code:
@org.hibernate.annotations.CollectionOfElements(targetElement=UserEnt.class, fetch=FetchType.EAGER)
@JoinTable(name="users_friends", joinColumns={@JoinColumn(name="user_id")})


When i add data if any value in either column is repeated i get a duplicate entry for key error.

Any workarounds or fixes?


Top
 Profile  
 
 Post subject:
PostPosted: Sat Mar 08, 2008 1:08 pm 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
Which collection type are you using? and show the actuall embedded value code

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Mon Mar 10, 2008 10:55 am 
Beginner
Beginner

Joined: Wed Mar 05, 2008 10:32 am
Posts: 48
I'm using
Code:
@Entity
@TableGenerator(name="ids_generator", table="IDS")
public class UserEnt {
...


and the collection
Code:
private Set<UserEnt> friends = new HashSet<UserEnt>();

@org.hibernate.annotations.CollectionOfElements(targetElement=UserEnt.class, fetch=FetchType.EAGER)
@JoinTable(name="users_friends", joinColumns={@JoinColumn(name="user_id")})
public Set<UserEnt> getFriends() {
   return friends;
}



Top
 Profile  
 
 Post subject:
PostPosted: Mon Mar 10, 2008 7:28 pm 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
Actually what's in the ... is important :)
Can you also show the schema export logs.

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Mon Mar 10, 2008 8:21 pm 
Beginner
Beginner

Joined: Wed Mar 05, 2008 10:32 am
Posts: 48
ok so here is my entire class
Code:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.TableGenerator;

import org.hibernate.annotations.CollectionOfElements;

/**
* The Class UserEnt.
*/
@Entity
@TableGenerator(name="ids_generator", table="IDS")
public class UserEnt {
   
   private Long id;
   private   String firstName;
   private String lastName;
   private String login;
   private String password;
   private String email;
   private boolean isFunctional = true;
   private PreferencesEmb preferences;
   private Long age;
   private String sex;
   private String income;
   private String cellPhone;
   private String residence;
   private String occupation;
   private String education;
   private ImageEmb avatar;
   private String rights;
   private AddressEmb address;
   private Collection<ImageEmb> images = new ArrayList<ImageEmb>();
   
//   private Set<UserEnt> friends = new HashSet<UserEnt>();
   
   private Set<EventEnt> inviteList = new HashSet<EventEnt>();
   private Set<EventEnt> attendingList = new HashSet<EventEnt>();
   private Set<EventEnt> notAttendingList = new HashSet<EventEnt>();

//   private Set<VenueEnt> favoriteVenues = new HashSet<VenueEnt>();
   
   //[begin] venue's images
   /**
    * Gets the images.
    *
    * @return the images
    */
   @org.hibernate.annotations.CollectionOfElements(fetch=FetchType.EAGER)
   @org.hibernate.annotations.CollectionId(
         columns = @Column(name = "USER_IMAGES_ID"),
         type = @org.hibernate.annotations.Type(type = "long"),
         generator = "ids_generator"
   )
   public Collection<ImageEmb> getImages() {
      return images;
   }

   /**
    * Sets the images.
    *
    * @param images the images
    */
   public void setImages(Collection<ImageEmb> images) {
      this.images = images;
   }

   
   /**
    * Gets the cell phone.
    *
    * @return the cellPhone
    */
   @Column(nullable = false)
   public String getCellPhone() {
      return cellPhone;
   }

   /**
    * Sets the cell phone.
    *
    * @param cellPhone the cellPhone to set
    */
   public void setCellPhone(String cellPhone) {
      this.cellPhone = cellPhone;
   }

   /**
    * Gets the residence.
    *
    * @return the residence
    */
   @Column(nullable = false)
   public String getResidence() {
      return residence;
   }

   /**
    * Sets the residence.
    *
    * @param residence the residence to set
    */
   public void setResidence(String residence) {
      this.residence = residence;
   }

   /**
    * Gets the occupation.
    *
    * @return the occupation
    */
   @Column(nullable = false)
   public String getOccupation() {
      return occupation;
   }

   /**
    * Sets the occupation.
    *
    * @param occupation the occupation to set
    */
   public void setOccupation(String occupation) {
      this.occupation = occupation;
   }

   /**
    * Gets the education.
    *
    * @return the education
    */
   @Column(nullable = false)
   public String getEducation() {
      return education;
   }

   /**
    * Sets the education.
    *
    * @param education the education to set
    */
   public void setEducation(String education) {
      this.education = education;
   }


   
   /**
    * Gets the age.
    *
    * @return the age
    */
   @Column(nullable = false, length = 1)
   public Long getAge() {
      return age;
   }

   /**
    * Sets the age.
    *
    * @param age the age to set
    */
   public void setAge(Long age) {
      this.age = age;
   }

   /**
    * Gets the sex.
    *
    * @return the sex
    */
   @Column(nullable = false)
   @org.hibernate.annotations.Check(constraints = "sex like 'male' or sex like 'female'")
   public String getSex() {
      return sex;
   }

   /**
    * Sets the sex.
    *
    * @param sex the sex to set
    */
   public void setSex(String sex) {
      this.sex = sex;
   }

   /**
    * Gets the income.
    *
    * @return the income
    */
   @Column(nullable = false, length = 20)
   public String getIncome() {
      return income;
   }

   /**
    * Sets the income.
    *
    * @param income the income to set
    */
   public void setIncome(String income) {
      this.income = income;
   }

   /**
    * Instantiates a new user ent.
    */
   public UserEnt() {
      this.preferences = PreferencesEmb.createDefaultPrefs();
      this.avatar = ImageEmb.createDefaultImage();
      this.address = AddressEmb.createDefaultAddress();
   }
   
   /**
    * Instantiates a new user ent.
    *
    * @param firstName the first name
    * @param lastName the last name
    * @param login the login
    * @param password the password
    * @param email the email
    * @param age the age
    * @param sex the sex
    * @param income the income
    * @param cellPhone the cell phone
    * @param occupation the occupation
    * @param residence the residence
    * @param education the education
    * @param isFunctional the is functional
    */
   public UserEnt(String firstName, String lastName, String login, String password, String email, Long age,
         String sex, String income, String cellPhone, String occupation, String residence, String education, boolean isFunctional) {
      super();
      this.firstName = firstName;
      this.lastName = lastName;
      this.login = login;
      this.password = password;
      this.email = email;
      this.isFunctional = isFunctional;
      this.preferences = PreferencesEmb.createDefaultPrefs();
      this.age = age;
      this.sex = sex;
      this.income = income;
      this.cellPhone = cellPhone;
      this.occupation = occupation;
      this.residence = residence;
      this.education = education;
      this.avatar = ImageEmb.createDefaultImage();
      this.address = AddressEmb.createDefaultAddress();
      this.rights = "user";
   }

   /**
    * Gets the id.
    *
    * @return the id
    */
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   public Long getId() {
      return id;
   }
   
   /**
    * Sets the id.
    *
    * @param userId the new id
    */
   public void setId(Long userId) {
      this.id = userId;
   }

   /**
    * Gets the email.
    *
    * @return the email
    */
   @Column(nullable = false, unique = true, length = 40)
   public String getEmail() {
      return email;
   }
   
   /**
    * Sets the email.
    *
    * @param email the new email
    */
   public void setEmail(String email) {
      this.email = email;
   }

   /**
    * Gets the first name.
    *
    * @return the first name
    */
   @Column(nullable = false, length = 20)
   public String getFirstName() {
      return firstName;
   }

   /**
    * Sets the first name.
    *
    * @param firstName the new first name
    */
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   /**
    * Checks if is functional.
    *
    * @return true, if is functional
    */
   @Column(nullable = false)
   public boolean isFunctional() {
      return isFunctional;
   }
   
   /**
    * Sets the functional.
    *
    * @param isFunctional the new functional
    */
   public void setFunctional(boolean isFunctional) {
      this.isFunctional = isFunctional;
   }

   /**
    * Gets the last name.
    *
    * @return the last name
    */
   @Column(nullable = false, length = 20)
   public String getLastName() {
      return lastName;
   }

   /**
    * Sets the last name.
    *
    * @param lastName the new last name
    */
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   /**
    * Gets the login.
    *
    * @return the login
    */
   @Column(nullable = false, length = 20, unique = true)
   public String getLogin() {
      return login;
   }
   
   /**
    * Sets the login.
    *
    * @param login the new login
    */
   public void setLogin(String login) {
      this.login = login;
   }

   /**
    * Gets the password.
    *
    * @return the password
    */
   @Column(nullable = false, length = 20)
   public String getPassword() {
      return password;
   }

   /**
    * Sets the password.
    *
    * @param password the new password
    */
   public void setPassword(String password) {
      this.password = password;
   }

   /**
    * Gets the preferences.
    *
    * @return the preferences
    */
   @Embedded
   public PreferencesEmb getPreferences() {
      return preferences;
   }

   /**
    * Sets the preferences.
    *
    * @param preferences the new preferences
    */
   public void setPreferences(PreferencesEmb preferences) {
      this.preferences = preferences;
   }

   /**
    * Gets the avatar.
    *
    * @return the avatar
    */
   @Embedded
   public ImageEmb getAvatar() {
      return avatar;
   }

   /**
    * Sets the avatar.
    *
    * @param avatar the avatar to set
    */
   public void setAvatar(ImageEmb avatar) {
      this.avatar = avatar;
   }

   /**
    * Gets the address.
    *
    * @return the address
    */
   @Embedded
   public AddressEmb getAddress() {
      return address;
   }

   /**
    * Sets the address.
    *
    * @param address the address to set
    */
   public void setAddress(AddressEmb address) {
      this.address = address;
   }

   /**
    * Gets the rights.
    *
    * @return the rights
    */
   @Column(nullable = false)
   public String getRights() {
      return rights;
   }

   /**
    * Sets the rights.
    *
    * @param rights the rights to set
    */
   public void setRights(String rights) {
      this.rights = rights;
   }

   /**
    * @return the inviteList
    */
   @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER, mappedBy="inviteList",   targetEntity=EventEnt.class)
   public Set<EventEnt> getInviteList() {
      return inviteList;
   }

   /**
    * @param inviteList the inviteList to set
    */
   public void setInviteList(Set<EventEnt> inviteList) {
      this.inviteList = inviteList;
   }
   
   /**
    * @param event the event
    */
   public void setInvited(EventEnt event) {
      this.inviteList.add(event);
   }

   /**
    * @param event the event
    */
   public void deSetInvited(EventEnt event) {
      this.inviteList.remove(event);
   }

   /**
    * @return the attendingList
    */
   @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER, mappedBy="attendingList",   targetEntity=EventEnt.class)
   public Set<EventEnt> getAttendingList() {
      return attendingList;
   }

   /**
    * @param attendingList the attendingList to set
    */
   public void setAttendingList(Set<EventEnt> attendingList) {
      this.attendingList = attendingList;
   }

   /**
    * @param event the event
    */
   public void setAttending(EventEnt event) {
      this.attendingList.add(event);
   }

   /**
    * @param event the event
    */
   public void deSetAttending(EventEnt event) {
      this.attendingList.remove(event);
   }

   /**
    * @return the notAttendingList
    */
   @ManyToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER, mappedBy="notAttendingList",   targetEntity=EventEnt.class)
   public Set<EventEnt> getNotAttendingList() {
      return notAttendingList;
   }

   /**
    * @param notAttendingList the notAttendingList to set
    */
   public void setNotAttendingList(Set<EventEnt> notAttendingList) {
      this.notAttendingList = notAttendingList;
   }

   /**
    * @param event the event
    */
   public void setNotAttending(EventEnt event) {
      this.notAttendingList.add(event);
   }

   /**
    * @param event the event
    */
   public void deSetNotAttending(EventEnt event) {
      this.notAttendingList.remove(event);
   }

   /**
    * Gets the friends.
    *
    * @return the friends
    */
//   @org.hibernate.annotations.CollectionOfElements(targetElement=UserEnt.class, fetch=FetchType.EAGER)
//   @JoinTable(name="users_friends", joinColumns={@JoinColumn(name="user_id")})
   //@OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER, mappedBy="friends", targetEntity=UserEnt.class)
//   public Set<UserEnt> getFriends() {
//      return friends;
//   }
   
   /**
    * Sets the friends.
    *
    * @param friends the friends
    */
//   public void setFriends(Set<UserEnt> friends) {
//      this.friends = friends;
//   }
   
   /**
    * Add a friend.
    *
    * @param friend the friend
    */
//   public void addFriend(UserEnt friend){
//      if (friend == null)
//         throw new IllegalArgumentException("adding null friend");
//      this.friends.add(friend);
//      friend.getFriends().add(this);
//   }
   
   /**
    * Removes a friend.
    *
    * @param friend the friend
    */
//   public void removeFriend(UserEnt friend){
//      if (friend == null)
//         throw new IllegalArgumentException("removing null friend");
//      this.friends.remove(friend);
//      friend.getFriends().add(null);
//   }
   
   /**
    * Gets the favorite venues.
    *
    * @return the favorite venues
    */
//   @OneToMany (cascade = {CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "user")
//   @org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.SAVE_UPDATE)
//   public Set<VenueEnt> getFavoriteVenues() {
//      return favoriteVenues;
//   }

   /**
   * Sets the favorite venues.
   *
   * @param favoriteVenues the favorite venues
   */
//   public void setFavoriteVenues(Set<VenueEnt> favoriteVenues) {
//      this.favoriteVenues = favoriteVenues;
//   }
   
   /**
   * Adds a favorite venue.
   *
   * @param venueEnt the venue ent
   */
//   public void addFavoriteVenue(VenueEnt venueEnt){
//      if (venueEnt == null)
//         throw new IllegalArgumentException("adding null venue");
//      this.favoriteVenues.add(venueEnt);
//      venueEnt.setUser(this);
//   }
   
   /**
   * Removes the favorite venue.
   *
   * @param venueEnt the venue ent
   */
//   public void removeFavoriteVenue(VenueEnt venueEnt){
//      if (venueEnt == null)
//         throw new IllegalArgumentException("removing null venue");
//      this.favoriteVenues.remove(venueEnt);
//      venueEnt.setUser(null);
//   }

}


How do i obtain my schema export logs?
I'm connecting to mySQL
and when i did a describe, i got both as primary keys. not sure if they are composite.

I appreciate your help.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Mar 11, 2008 1:18 pm 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
Enable this category in log4j
org.hibernate.tool.hbm2ddl=debug

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 12, 2008 11:33 am 
Beginner
Beginner

Joined: Wed Mar 05, 2008 10:32 am
Posts: 48
Code:
    create table UserEnt (
        id bigint not null auto_increment,
        address1 varchar(150),
        address2 varchar(150),
        area varchar(100),
        city varchar(100),
        state varchar(100),
        zip varchar(9),
        age bigint not null,
        comment varchar(255),
        dateAdded datetime not null,
        location varchar(255) not null,
        title varchar(255) not null,
        cellPhone varchar(255) not null,
        education varchar(255) not null,
        email varchar(40) not null unique,
        firstName varchar(20) not null,
        functional bit not null,
        income varchar(20) not null,
        lastName varchar(20) not null,
        login varchar(20) not null unique,
        occupation varchar(255) not null,
        password varchar(20) not null,
        receiveMobileCalls bit not null,
        receiveMobileText bit not null,
        receiveNewsletter bit not null,
        resultCount bigint not null,
        residence varchar(255) not null,
        rights varchar(255) not null,
        sex varchar(255) not null,
        primary key (id)
    )

    create table users_friends (
        user_id bigint not null,
        friends_id bigint not null,
        primary key (user_id, friends_id),
        unique (friends_id)
    )

    alter table users_friends
        add index FK126F65E4991CD9D (user_id),
        add constraint FK126F65E4991CD9D
        foreign key (user_id)
        references UserEnt (id)

    alter table users_friends
        add index FK126F65EE9B02393 (friends_id),
        add constraint FK126F65EE9B02393
        foreign key (friends_id)
        references UserEnt (id)


And for my insert code
Code:
UserEnt user1 = new UserEnt("John", "Doe", "user1", "pass1", "john_doe@infosys.com", new Long(21), "male", "$$", "212212212", "worker", "home", "college", true);

UserEnt user2 = new UserEnt("Mike", "Smith", "user2", "pass2", "user2@user.com", new Long(24), "male", "212212212", "worker", "home", "$$$", "college", true);

UserEnt user3 = new UserEnt("Jack", "Black", "user3", "pass3", "user3@user.com", new Long(24), "male", "212212212", "worker", "home", "$$$", "college", true);

user1.addFriend(user2);
user1.addFriend(user3);
user3.addFriend(user1);
user3.addFriend(user2);

session.save(user1);
session.save(user2);
session.save(user3);


And that insert script fails resulting in...
Not sure why there are so many insert statements either

Code:
10:22:58,657 DEBUG SQL:401 -
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
Hibernate:
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
10:22:58,672 DEBUG SQL:401 -
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
Hibernate:
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
10:22:58,672 DEBUG SQL:401 -
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
Hibernate:
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
10:22:58,672 DEBUG SQL:401 -
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
Hibernate:
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
10:22:58,672 DEBUG SQL:401 -
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
Hibernate:
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
10:22:58,672 DEBUG SQL:401 -
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
Hibernate:
    insert
    into
        users_friends
        (user_id, friends_id)
    values
        (?, ?)
10:22:58,672  WARN JDBCExceptionReporter:77 - SQL Error: 1062, SQLState: 23000
10:22:58,672 ERROR JDBCExceptionReporter:78 - Duplicate entry '1' for key 2
10:22:58,672 ERROR AbstractFlushingEventListener:301 - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
   at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
   at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
   at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
   at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:92)
   at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:87)
   at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:222)
   at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1119)
   at org.hibernate.action.CollectionRecreateAction.execute(CollectionRecreateAction.java:26)
   at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234)
   at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:145)
   at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
   at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
   at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
   at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
   at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
   at com.epixentertainment.util.InsertDbData.doInserts(InsertDbData.java:69)
   at com.epixentertainment.util.InsertDbData.main(InsertDbData.java:44)
Caused by: java.sql.BatchUpdateException: Duplicate entry '1' for key 2


Top
 Profile  
 
 Post subject:
PostPosted: Thu Mar 13, 2008 3:07 pm 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
From what I can see the schema generation comes from a different mapping
Probably something like

Code:
@OneToMany
@JoinTable
Set<UserEnt> friends;


But if you look at it it's a one to many between UserEnt and UserEnt which says a User can have many friend but a friend (which is a user) can have only one User.
This does not make much sense in your model, so what you want is a @ManyToMany

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Thu Mar 13, 2008 4:58 pm 
Beginner
Beginner

Joined: Wed Mar 05, 2008 10:32 am
Posts: 48
Fantastic!
Many thanks Emmanuel.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 9 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.