【问题标题】:Hibernate Relationships AnnotationsHibernate 关系注解
【发布时间】:2015-05-07 22:05:39
【问题描述】:

使用@ManyToOne 和@OneToMany 如何定义下表之间的关系。我是休眠新手,不确定我的工作是否正确。路由表中的两个外键是否需要两个单独的关系注释?

MySQL:

CREATE TABLE BusStop ( 
ID int NOT NULL,
Description varchar(40) NOT NULL,
PRIMARY KEY (ID))
Engine=InnoDB;

CREATE TABLE Route ( 
Route_Number int NOT NULL,
Destination int NOT NULL
Frequency int NOT NULL,
Start int NOT NULL,
PRIMARY KEY (Route_Number),
FOREIGN KEY (Destination) 
REFERENCES BusStop(ID),
FOREIGN KEY (Start) REFERENCES BusStop(ID) 
Engine=InnoDB

BusStop.java:

public class BusStop {

public static final String SELECT_ALL = "BusStop.selectAll";

@Id
@Column(name = "id")
private int id;

@Column(name = "description")
private String description;

public BusStop(){}
public int getId(){
    return id;
}

public void setId(int id){
    this.id = id;
}

public void setDescription( String description ) {
    this.description = description;
 }

public String getDescription() {
    return description;
 }

@OneToMany(mappedBy="startRef")
private Set<Route> startStop;

@OneToMany(mappedBy="destRef")
private Set<Route> destStop;

}

Route.java

@Table(name = "route")
public class Route {
public static final String SELECT_ALL = "Route.selectAll";

@Id
@Column(name = "route_number")
private int route_number;

@Column(name = "destination")
private int destination;

@Column(name = "frequency")
private int frequency;

@Column(name = "start")
private int start;

private Set<Operator> operators = new HashSet<Operator>();

public Route(){}

// getters & setters

@ManyToOne
@JoinColumn(name="start")
private BusStop startRef;

@ManyToOne
@JoinColumn(name="destination")
private BusStop destRef;

感谢您的帮助。

【问题讨论】:

    标签: java mysql hibernate


    【解决方案1】:

    一般没问题。将 Route 更新到这些以使用密钥。请注意,您有这些值只是更正了列名

    @ManyToOne
    @JoinColumn(name="id")
    private BusStop startRef;
    
    
    @ManyToOne
    @JoinColumn(name="id")
    private BusStop destRef;
    

    【讨论】:

      猜你喜欢
      • 2012-06-03
      • 2012-07-13
      • 2020-08-05
      • 1970-01-01
      • 2016-05-07
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多