michael112 wrote:
You have to put id field in FileData as well but you also have to specify how you want Hibernate to generate values for it:
@Id @GeneratedValue(generator = "myForeignGenerator")
@org.hibernate.annotations.GenericGenerator(
name = "myForeignGenerator",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "file"))
private Long id;
This way it will pick up Id value from the entity property "file" and all will work as expected. You have to assign File property value before you persist FileData but this is what you are after anyway.
That helped me but i still have one issue: I now have a duplicate column in the database. What I want to have in the database is a table like this:
CREATE TABLE `FileData` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_FileData` FOREIGN KEY (`id`) REFERENCES `File` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
)
and a File table like this:
CREATE TABLE `File` (
`id` int(11) NOT NULL auto_increment,
`contentType` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
Following your post, I have a FileData class like this:
@Entity
public class FileData {
@Id
@GeneratedValue(generator = "myForeignGenerator")
@GenericGenerator(
name = "myForeignGenerator",
strategy = "foreign",
parameters = @Parameter(name = "property", value = "file"))
private int id;
@Basic(optional=false)
private String name;
@OneToOne()
@JoinColumn()
private File file;
}
But this results in a table like this:
CREATE TABLE `FileData` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`file_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK92C29CB08A7A8DE9` (`file_id`)
CONSTRAINT `FK92C29CB08A7A8DE9` FOREIGN KEY (`file_id`) REFERENCES `File` (`id`)
)
So, I have an Id in FileData that takes its value from the File associated but I have also a file_id (from the OneToOne association) that has of course the same value id column has, and the Foreign key association is on this one, not on the id column....
Can these be done?
Thanks for your help, Michael.