學生、課程、分數的設計(重要)
表設計:
方法1:
設定聯合主鍵@EmbeddedId
實作Serializable接口
student:id<int> name<String>
course:id<int> name<String>
score:studentid<int> courseid<int> score<int>//聯合主鍵聯合id
//有點麻煩不寫了,直接看方法2吧
方法2:
score:id<int> studentid<int> courseid<int> score<int>//這一方設ManyToOne
實作代碼:
Student.java:
Score.java:
Course.java:
在hibernate.cfg.xml配置:
建表語句:
create table s_course (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
create table s_score (
id integer not null,
score integer not null,
course_id integer,
student_id integer not null auto_increment,
primary key (student_id, course_id)
create table s_student (
alter table s_score
add index FK6C0C3FC68B2C002E (student_id),
add constraint FK6C0C3FC68B2C002E
foreign key (student_id)
references s_student (id)
add index FK6C0C3FC6EFAFE106 (course_id),
add constraint FK6C0C3FC6EFAFE106
foreign key (course_id)
references s_course (id)
結果:
score:id<int> studentid<int> courseid<int> score<int>
測試添加:
Hibernate:
insert
into
s_student
(name)
values
(?)
s_course
s_score
(course_id, score, student_id)
(?, ?, ?)
測試取資料:
select
student0_.id as id0_0_,
student0_.name as name0_0_
from
s_student student0_
where
student0_.id=?
courses0_.student_id as student4_0_1_,
courses0_.course_id as course3_1_,
course1_.id as id2_0_,
course1_.name as name2_0_
s_score courses0_
inner join
s_course course1_
on courses0_.course_id=course1_.id
courses0_.student_id=?
java