1、在Hibernate中,Many2One的基于注解Annotation的实现
2、Student.java的代码(带注解,注意注解是在哪个包下的)
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue
private int id;
@Column(name = "age")
private int age;
private String name;
// 持有多的一方为外键
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "classid", referencedColumnName = "id")
// 外键为classid,与classRoom中的id关联(默认的话,是和表中的主键向关联)
private ClassRoom classRoom;
// get set
}
3、ClassRoom.java的代码(带注解,注意注解是在哪个包下的)
import javax.persistence.Table;
@Entity
@Table(name = "classroom")
public class ClassRoom {
@Id
@GeneratedValue
private int id;
private String classRoomName;
// get set
}
4、hibernate.cfg.xml的配置
4.1 将Student.java和ClassRoom.java,加入到hibernate.cfg.xml的配置文件里面
<!--3.加载实体的映射文件 ,采用注解的时候 -->
<mapping class="com.hibernate.entity.ClassRoom" />
<mapping class="com.hibernate.entity.Student" />
4.2 hibernate.cfg.xml的配置的完整内容
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<!-- 通常,一个session-factory节点代表一个数据库 -->
<session-factory>
<!-- 1. 数据库连接配置 -->
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql:///hibernate
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 2. 其他相关配置 -->
<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 2.2 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!-- 2.3 自动建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--3.加载实体的映射文件 ,采用注解的时候 -->
<mapping class="com.hibernate.entity.ClassRoom" />
<mapping class="com.hibernate.entity.Student" />
</session-factory>
</hibernate-configuration>
5、测试代码
public class HibernateTest {
@Test
public void testmany2one() {
Student stu1 = new Student();
stu1.setAge(18);
stu1.setName("18");
Student stu2 = new Student();
stu2.setAge(19);
stu2.setName("19");
ClassRoom classRoom = new ClassRoom();
classRoom.setClassRoomName("计算机技术");
// 增加Student和ClassRoom的注册关系
stu1.setClassRoom(classRoom);
stu2.setClassRoom(classRoom);
// 保存到数据库
IClassRoomDao roomDao = new ClassRoomDaoImpl();
IStudentDao studentDao = new StudentDaoImpl();
// 在保存一的一方
roomDao.add(classRoom);
// 先保存多的一方
studentDao.add(stu1);
studentDao.add(stu2);
}
}
6、代码下载