(12)基于annotation配置ManyToOne
程序员文章站
2022-04-12 17:45:19
...
@Entity
@Table(name="t_cla")
public class Classroom {
private int id;
private String name;
private int grade;
private Set<Student> stus;
@OneToMany(mappedBy="cla")//表示由对方即多的一方(stu)的cla属性维护关系
@LazyCollection(LazyCollectionOption.EXTRA)//表示由cla取stus的size时,智能化,使用count
public Set<Student> getStus() {
return stus;
}
public void setStus(Set<Student> stus) {
this.stus = stus;
}
@Id
@GeneratedValue//相当于native
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="cla_name")//把name在数据库表示为cla_name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
@Entity
@Table(name="t_stu")
public class Student {
private int id;
private String name;
private int number;
private Classroom cla;
@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;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@ManyToOne(fetch=FetchType.LAZY)//由stu取cla时,使用延迟加载
@JoinColumn(name="c_id")
public Classroom getCla() {
return cla;
}
public void setCla(Classroom cla) {
this.cla = cla;
}
}
hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_01</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">HZP123</property>
<property name="show_sql">true</property>
<!-- <mapping resource="model/User.hbm.xml"/>
<mapping resource="model/Book.hbm.xml"/>
<mapping resource="model/Classroom.hbm.xml"/>
<mapping resource="model/Student.hbm.xml"/>
<mapping resource="model/Message.hbm.xml"/>
<mapping resource="model/Comment.hbm.xml"/>
<mapping resource="model/Person.hbm.xml"/>
<mapping resource="model/IdCard.hbm.xml"/>
<mapping resource="model/Admin.hbm.xml"/>
<mapping resource="model/Role.hbm.xml"/>
<mapping resource="model/TeacherCourse.hbm.xml"/>
<mapping resource="model/Teacher.hbm.xml"/>
<mapping resource="model/Course.hbm.xml"/> -->
<mapping class="model.Classroom"/><!-- 这里使用的是xx.xx 而不是xx/xx -->
<mapping class="model.Student"/>
</session-factory>
</hibernate-configuration>