hibernate 注解方式配置onetomany 非主键级联


配置完成后级联保存可以(从对象是与主对象的name关联,并不是id主键),但是在执行查询时,二次查询从对象的sql语句貌似还是拿主对象的id来与从对象的外键关联,所以查询不出从对象的集合。估计是注解的配置没配好,谁有好的办法?
具体配置代码:

@Entity
public class Student {
private String id; //编号
private String name; //名称
private Set<Score> scoreSet=new HashSet<Score>();
@Id
@Column(length=12)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@OneToMany(cascade=CascadeType.ALL,mappedBy="student")
@JoinColumn(name="student_name")
public Set<Score> getScoreSet() {
return scoreSet;
}
public void setScoreSet(Set<Score> scoreSet) {
this.scoreSet = scoreSet;
}
public void addScore(Score score){
score.setStudent(this); //成绩与学生关联
scoreSet.add(score);//学生添加成绩单
}
public String toString(){
return "id:"+id+";name:"+name;
}
}

@Entity
public class Score {
private int id;
private String type;
private Student student;

@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
} @ManyToOne
@JoinColumn(name="student_name",referencedColumnName="name")//主要是这里,关联的是学生的name而不是学生的id
@ForeignKey(name="fk_student_name")
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}

![执行保存代码]

保存时,控制台的sql代码

生成的表结构

执行的查询代码

控制台输出的查询代码:

Hibernate: select student0_.id as id0_0_, student0_.name as name0_0_ from Student student0_ where student0_.id=?
id:123;name:AA
Hibernate: select scoreset0_.student_name as student3_1_, scoreset0_.id as id1_, scoreset0_.id as id1_0_, scoreset0_.student_name as student3_1_0_, scoreset0_.type as type1_0_ from Score scoreset0_ where scoreset0_.student_name=?

级联查询时怎么是用的id来关联?

保存代码

hibernate

HC夕``彐 11 years, 2 months ago

Your Answer