Reputation: 999
I have two tables (already created), say Person and Address with following schemas:
create table Person (
`id` int(11) not null auto_increment,
`name` varchar(255) default null,
primary key(`id`)
)
create table Address (
`id` int(11) not null,
`city` varchar(255) default null,
primary key (`id`),
constraint foreign key (`id`) references `Person`(`id`)
)
Now, which annotations should I use in the code?
The skeletons of both the classes are:
class Person {
@Id @GeneratedValue
@Column(name="id")
int id;
String name;
Address address;
}
class Address {
int id;
}
I need to add annotations for address field in Person class and id field of Address class.
Upvotes: 0
Views: 188
Reputation: 19892
I think you want to use @MapsId.
@Entity
class Person {
@Id
@GeneratedValue
int id;
String name;
@OneToOne
@MapsId
Address address;
}
@Entity
class Address {
@Id
int id;
}
Check out example 2 in the @OneToOne documentation.
Upvotes: 0
Reputation: 8014
in Person.java
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "id",nullable=false)
@ForeignKey(name = "fk_id")
private Address address;
and in Address .java -
@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "id", updatable = false, insertable = false, nullable=false)
private Person id;
@Column(name = "id", insertable = false, updatable = false, nullable=false)
private Integer id;
Upvotes: 1
Reputation: 859
class Person {
@Id @GeneratedValue
@Column(name="id")
int id;
String name;
@OneToOne
@JoinColumn(name = "address_id", referencedColumnName = "id")
Address address;
}
class Address {
@id
int id;
}
Upvotes: 0