使用注解的方式进行一对一单向外键关联设置。如下:
(1)Wife类
- package com.yy.hibernate.model;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- @Entity
- public class Wife {
- private int id;
- private String name;
- @Id
- @GeneratedValue
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
(2)Husband类
- package com.yy.hibernate.model;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.OneToOne;
- @Entity
- public class Husband {
- private int id;
- private String name;
- private Wife wife;
- @Id
- @GeneratedValue
- public int getId() {
- return id;
- }
- public String getName() {
- return name;
- }
- @OneToOne
- @JoinColumn(name="wifeId")
- public Wife getWife() {
- return wife;
- }
- public void setId(int id) {
- this.id = id;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void setWife(Wife wife) {
- this.wife = wife;
- }
- }
(3)SchemaExport
- new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
自动生成的表如下:
- mysql> desc husband;
- +--------+--------------+------+-----+---------+----------------+
- | Field | Type | Null | Key | Default | Extra |
- +--------+--------------+------+-----+---------+----------------+
- | id | int(11) | NO | PRI | NULL | auto_increment |
- | name | varchar(255) | YES | | NULL | |
- | wifeId | int(11) | YES | MUL | NULL | |
- +--------+--------------+------+-----+---------+----------------+
- mysql> desc wife;
- +-------+--------------+------+-----+---------+----------------+
- | Field | Type | Null | Key | Default | Extra |
- +-------+--------------+------+-----+---------+----------------+
- | id | int(11) | NO | PRI | NULL | auto_increment |
- | name | varchar(255) | YES | | NULL | |
- +-------+--------------+------+-----+---------+----------------+
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于