Reputation: 173
Okay, so I have 2 tables on an Oracle DB that I want to represent in Java with Spring 3 and Hibernate 3. They have a Many to One relationship, and the tables are something like
CAR
-------
CAR_PK
//... other columns
OPTION
------
CAR_FK
OPTION_TEXT
//... other columns
because the Options table is only meaningful with respect to the Car, we only care about accessing it when the Car is accessed, so it doesn't have a unique PK of its own. Furthermore, there can be more than 1 Option per car. Therefore, we are using a composite id of CAR_FK and OPTIONS_TEXT
the java is something like
public class Car{
@Id
@Column(name="CAR_PK")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="CAR_KEY_SEQ")
@SequenceGenerator (name="CAR_KEY_SEQ", sequenceName="CAR_KEY_SEQ", allocationSize=1)
private long carPk;
@OneToMany(cascade= CascadeType.ALL, mappedBy="car")
@JoinColumn(name="CAR_PK")
private List<Option> options;
//... other stuff
}
@IdClass(OptionId.class)
public class Option{
@Id
private long carFk;
@Id
private String optionText;
@ManyToOne
@JoinColumn(name="CAR_FK")
private Car car;
//... other stuff
}
@Emeddable
public class OptionId implements Serializable{
@Column(CAR_FK)
private long carFk;
@Column(OPTION_TEXT)
private String optionText
//... other stuff
}
On insert, I want the same key generated for carPk in the Car object to be inserted for carFk in the Option object. How do I do this?I get
java.sql.SQLException: Invalid column index
What am I doing wrong?
Upvotes: 0
Views: 304
Reputation: 684
First thing is since Option has no existence of its own it should not be an Entity. Only Car is an Entity Object whereas Option is a value Object so it should not have any id of its own.
You could change the design as
@Entity
public class Car{
@Id
@Column(name="CAR_PK")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="CAR_KEY_SEQ")
@SequenceGenerator (name="CAR_KEY_SEQ", sequenceName="CAR_KEY_SEQ", allocationSize=1)
private long carPk;
@Embedded
private List<Option> options;
//... other stuff
}
@Embeddable
public class Option{
private String optionText;
//... other stuff
}
That should solve all your problems.
Upvotes: 2
Reputation: 9
You do have a typo in your above code when defining your cascade type:
@OneToMany(cascase= CascadeType.ALL, mappedBy="car")
This could be causing your Invalid column index.
Upvotes: 1