时间:2021-07-01 10:21:17 帮助过:2人阅读
2、学生表
package pojo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="student",catalog="school") public class Student { private int student_id; private String student_name; private Grade grade; @GenericGenerator(name="generator",strategy="increment") @Id @GeneratedValue(generator="generator") @Column(name="id",unique=true,nullable=false) public int getStudent_id() { return student_id; } public void setStudent_id(int student_id) { this.student_id = student_id; } @Column(name="student_name",length=50) public String getStudent_name() { return student_name; } public void setStudent_name(String student_name) { this.student_name = student_name; } //延迟加载,设置学生表的外键 @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="grade_id") public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } }
3、Hibernate配置文件hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!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> <!--数据库连接相关--> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="connection.url"> jdbc:mysql://localhost:3306/school?characterEncoding=utf8 </property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- 辅助参数 --><!--数据库方言,提示HIbernate使用恰当的sql语句--> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- 将当前会话绑定到线程 --> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 添加使用Hibernate注解的实体Bean,而不是映射文件 --> <mapping class="pojo.Grade" /> <mapping class="pojo.Student"/> </session-factory> </hibernate-configuration>
---恢复内容结束---
1、Hibernate注解实现对象关联映射并自动生成数据库表
标签: