码迷,mamicode.com
首页 > Web开发 > 详细

hibernate多对一单向关联注解方式

时间:2015-10-28 14:22:43      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

多对一单向关联,在多的一方加上一的一方作为外键。在程序里表现为:在多的一方加上一的引用。

小组类Group,用户User:

Group:

package com.oracle.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="t_group")//group是mysql的关键字,换个名
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 com.oracle.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class User {

    private int id;
    private String name;
    private Group  group;
    
    //多对一
    @ManyToOne
    @JoinColumn(name="groupId")//指定外键名称
    public Group getGroup() {
        return group;
    }
    public void setGroup(Group group) {
        this.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;
    }
    
}

 

生成的表:可以看到在User里加了外键

技术分享

hibernate建表语句:

create table User (
id integer not null auto_increment,
name varchar(255),
groupId integer,
primary key (id)
)

 

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

在User里加了外键:

alter table User
add index FK285FEB744AEC3A (groupId),
add constraint FK285FEB744AEC3A
foreign key (groupId)
references t_group (id)

hibernate多对一单向关联注解方式

标签:

原文地址:http://www.cnblogs.com/lihaoyang/p/4917078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!