-->
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.  [ 5 posts ] 
Author Message
 Post subject: Another @IdClass, composite key and @OneToMany problem!
PostPosted: Fri Mar 02, 2007 10:55 pm 
Newbie

Joined: Fri Mar 02, 2007 10:34 pm
Posts: 6
Like another recent poster, I am trying to set up what seems like a very simple one-to-many relationship, but having no luck. When I try to start my application, the validator tells me I'm missing a column. I'm new to Hibernate and Java Persistence, so I suspect I'm missing something basic.

I have a small schema with two tables:

Code:
create table floors (
  id integer primary key
);

create table rooms (
  floor_id integer,
  number integer,
  primary key(floor_id, number),
  constraint foreign key (floor_id) references floors(id)
);


I also have two entities:

Code:
@Entity
@Table(name="floors")
public class Floor {
    private int id;
    private List<Room> rooms;
   
    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
   
    @OneToMany(cascade=CascadeType.ALL, mappedBy="floor")
    public List<Room> getRooms() {
        return rooms;
    }
    public void setRooms(List<Room> rooms) {
        this.rooms = rooms;
    }
}

Code:
@Entity
// Remove next line to make validation work
@IdClass(hotel.RoomKey.class)
@Table (name="rooms")
public class Room {
    private int floorId;
    private int number;
    private Floor floor;
   
// Remove next line to make validation work
    @Id
    @Column(name="floor_id")
    public int getFloorId() {
        return floorId;
    }
    public void setFloorId(int floorId) {
        this.floorId = floorId;
    }
   
    @Id
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
   
    @ManyToOne
    @JoinColumn(name="floor_id", insertable=false, updatable=false)
    public Floor getFloor() {
        return floor;
    }
    public void setFloor(Floor floor) {
        this.floor = floor;
    }
}


I also have a composite key class:

Code:
// Do I need this annotation? It doesn't seem to work either way.
@Embeddable
public class RoomKey implements Serializable {
    private static final long serialVersionUID = 4226995603575410303L;
   
    private int floorId;
    private int number;
   
    public int getFloorId() {
        return floorId;
    }
    public void setFloorId(int cardSetId) {
        this.floorId = cardSetId;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int position) {
        this.number = position;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        else if (o instanceof RoomKey) {
            return floorId == ((RoomKey)o).getFloorId() &&
                number == ((RoomKey)o).getNumber();
        }
        return false;
    }
   
    @Override
    public int hashCode() {
        return floorId ^ number;
    }
}


Finally, my main class tries to create a SessionFactory:
Code:
                    AnnotationConfiguration config = new AnnotationConfiguration();
                    config.configure();
                    sessionFactory = config.buildSessionFactory();


This fails with the following message:
Quote:
Exception in thread "main" java.lang.ExceptionInInitializerError
at hotel.HibernateTest$HibernateUtil.<clinit>(HibernateTest.java:29)
at hotel.HibernateTest.main(HibernateTest.java:13)

Caused by: org.hibernate.HibernateException: Missing column: floorId in hotel.rooms
at org.hibernate.mapping.Table.validateColumns(Table.java:254)
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1083)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:116)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:317)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at hotel.HibernateTest$HibernateUtil.<clinit>(HibernateTest.java:26)


If I remove the two marked lines (the @IdClass and one of the @Id tags) from Room, validation works fine. I guess when I leave them in Hibernate is ignoring my @Column and looking for a column with a default name...? But even if that's so, I don't really understand why. I'm stymied, and I've barely started! Hopefully one of you will be able to diagnose this easily - I'm sure I'm missing something very basic. Thanks in advance for your help!


Top
 Profile  
 
 Post subject:
PostPosted: Tue Mar 06, 2007 6:46 am 
Newbie

Joined: Tue Feb 13, 2007 10:27 am
Posts: 4
AFAIK you have to use a RoomKey member in Room instead of the floorId and number members:
Code:
@Entity
// Remove next line to make validation work
@IdClass(hotel.RoomKey.class)
@Table (name="rooms")
public class Room {
   private Roomkey id;

   @Id
   public RoomKey getId () {...}

   ...
}

_________________
Oliver


Top
 Profile  
 
 Post subject:
PostPosted: Tue Mar 06, 2007 4:01 pm 
Newbie

Joined: Fri Mar 02, 2007 10:34 pm
Posts: 6
Good idea, thanks revilo! I modified the code based on your suggestion and got around the validation problem. Unfortunately, I have now run into an additional problem. When I attempt to add a Room (number=199) to a Floor (id=1) and persist them to the database, I get this exception:

Quote:
org.hibernate.exception.GenericJDBCException: could not insert: [hotel.Room]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2263)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2656)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:52)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:232)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:139)
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 hotel.HibernateTest.main(HibernateTest.java:34)

Caused by: java.sql.SQLException: Parameter index out of bounds. 3 is not between valid values of 1 and 2
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.ServerPreparedStatement.getBinding(ServerPreparedStatement.java:768)
at com.mysql.jdbc.ServerPreparedStatement.setInt(ServerPreparedStatement.java:1778)
at org.hibernate.type.IntegerType.set(IntegerType.java:41)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:136)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:116)
at org.hibernate.type.ComponentType.nullSafeSet(ComponentType.java:284)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2004)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2239)
... 9 more


It looks like Hibernate is generating an extra parameter for an insert statement. But the statement itself looks ok:

Quote:
2007-03-06 14:46:09,140 DEBUG [org.hibernate.SQL] - <insert into rooms (floor_id, number) values (?, ?)>
Hibernate: insert into rooms (floor_id, number) values (?, ?)
2007-03-06 14:46:09,187 INFO [org.hibernate.type.IntegerType] - <could not bind value '199' to parameter: 3; Parameter index out of bounds. 3 is not between valid values of 1 and 2>


The correct parameters should be (1, 199). I don't see the actual parameters Hibernate is trying to bind anywhere in the output, but I'm guessing they're (1, 199, 199) and Hibernate thinks there's a second column for the room number. But I don't know why. Any more thoughts?

The latest Floor class has a new method, addRoom():

Code:
@Entity
@Table(name="floors")
public class Floor {
    private int id;
    private List<Room> rooms;
   
    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
   
    @OneToMany(cascade=CascadeType.ALL, mappedBy="floor")
    public List<Room> getRooms() {
        return rooms;
    }
    public void setRooms(List<Room> rooms) {
        this.rooms = rooms;
    }
    public void addRoom(Room room) {
        room.setFloor(this);
        rooms.add(room);
    }
}


While Room and RoomKey have been more extensively updated:

Code:
@Entity
@IdClass(hotel.RoomKey.class)
@Table (name="rooms")
public class Room {
    private Floor floor;
    private RoomKey id;
   
    public Room() {
        id = new RoomKey();
    }

    @Id
    public RoomKey getId () {
        return id;
    }

    public void setId(RoomKey id) {
        this.id = id;
    }

    public int getFloorId() {
        return id.getFloorId();
    }
    public void setFloorId(int floorId) {
        id.setFloorId(floorId);
    }

    public int getNumber() {
        return id.getNumber();
    }
    public void setNumber(int number) {
        id.setNumber(number);
    }

    @ManyToOne
    @JoinColumn(name="floor_id", insertable=false, updatable=false)
    public Floor getFloor() {
        return floor;
    }
    public void setFloor(Floor floor) {
        this.floor = floor;
    }
}


Code:
@Embeddable
public class RoomKey implements Serializable {
    private static final long serialVersionUID = 4226995603575410303L;
   
    private int floorId;
    private int number;
   
    @Column(name="floor_id", insertable=false, updatable=false)
    public int getFloorId() {
        return floorId;
    }
    public void setFloorId(int cardSetId) {
        this.floorId = cardSetId;
    }

    public int getNumber() {
        return number;
    }
    public void setNumber(int position) {
        this.number = position;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        else if (o instanceof RoomKey) {
            return floorId == ((RoomKey)o).getFloorId() &&
                number == ((RoomKey)o).getNumber();
        }
        return false;
    }
   
    @Override
    public int hashCode() {
        return floorId ^ number;
    }
}


I've been playing with @EmbeddedId vs @IdClass, and so far I haven't gotten @EmbeddedId to work, although apparently I do need to put @Embeddable in my key. I feel like I haven't quite got matching annotations from one class to the next, so I'm going to try playing around with that next. Also I think I'll try to let Hibernate generate my table and see what it comes up with.


Top
 Profile  
 
 Post subject: progress
PostPosted: Tue Mar 06, 2007 4:30 pm 
Newbie

Joined: Fri Mar 02, 2007 10:34 pm
Posts: 6
Ok, I modified RoomKey and changed the name of the field from floorId to floor_id. I then removed the @Column annotation from RoomKey.getFloorId() (or getFloor_id as it's now called). I also removed the getFloorId() and setFloorId() methods from Room. Now, as long as I populate the primary key myself, I am able to add a new room to a floor. So that's definitely progress. There are still two problems:

1) floor_id is a bad name for a Java field. I think there's some confusion coming from the fact that the reference to the parent entity is called "floor", and changing the name of floorId to floor_id works around that. But what I thought was supposed to work around it (using an @Column annotation) doesn't. So I have to figure out how to get a useable name into this field. Maybe if I rename Room.floor to Room.parent or something it will fix it.

2) When I call floor.addRoom(Room), the Room's setFloor_id() method is never called. The floor_id doesn't get set unless I do it myself. But that kind of defeats the purpose of using Hibernate here. Again I'm sure the overlap of a primary key and a one-to-many relationship is what's causing me problems here, since I've got exactly the same thing working fine in another situation where the two don't overlap. So, for that matter, has everybody else.

So back to the drawing board, I guess, but at least some clear forward progress has been made by this newbie. Any more help will be greatly appreciated, of course!


Top
 Profile  
 
 Post subject:
PostPosted: Mon Aug 06, 2007 9:23 am 
Newbie

Joined: Wed Mar 02, 2005 10:52 am
Posts: 7
Hey man, did you manage to get this working?

I am facing EXACTLY the same problem, as stated in this thread: http://forum.hibernate.org/viewtopic.php?t=978230

Would u have any hint?

Thanks!


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