你的位置:首页 > Java教程

[Java教程]hibernate(七)组件映射与多对一映射


一、组件映射

用注解配置组件映射:

Husband为我们映射的类,wife是这个类的一部分(属性不能与husband中属性重名,不要写Entity注解,不要有主键)

Husband类:(在getWife()方法上添加注解@Embedded)

package cn.orlion.hibernate.model;import javax.persistence.Embedded;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic class Husband {    private int id;    private String name;    private Wife wife;    @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;  }  @Embedded  public Wife getWife() {    return wife;  }  public void setWife(Wife wife) {    this.wife = wife;  }}

wife类:

package cn.orlion.hibernate.model;public class Wife {    private String wifename;  public String getWifename() {    return wifename;  }  public void setWifename(String wifename) {    this.wifename = wifename;  }}

建表语句:

create table Husband (    id integer not null auto_increment,    name varchar(255),    wifename varchar(255),    primary key (id)  )

 

二、多对一映射

1、多对一单向映射

注解方式配置:(一个组有多个用户,每个用户对应一个组,user是多的一方,group是一)

Group类:

package cn.orlion.hibernate.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;/* * 一个组有多个用户,每个用户对应一个组,user是多的一方,group是一 */@Entity@Table(name="t_group")public class Group {  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;  }}

 

User类:

package cn.orlion.hibernate.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToOne;import javax.persistence.Table;@Entity@Table(name="t_user")public class User {  private int id;    private String name;    private Group group;  @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;  }  @ManyToOne  public Group getGroup() {    return group;  }  public void setGroup(Group group) {    this.group = group;  }}

 

hibernate生成的sql:

create table t_group (    id integer not null auto_increment,    name varchar(255),    primary key (id)  )create table t_user (    id integer not null auto_increment,    name varchar(255),    group_id integer,    primary key (id)  )alter table t_user     add constraint FK_e5f24mh6aryt9hsy99oydps6g     foreign key (group_id)     references t_group (id)