三。Hibernate 注解形式

时间:2021-05-18 15:32:05

Hibernate支持JPA注解的jar包

三。Hibernate 注解形式

JPA全称: Java Persistence API

JPA和Hibernate之间的关系,可以简单的理解为JPA是标准接口,Hibernate是实现。

使用注解的形式进行配置可以代替实体类的 *.hbm.xml 的映射配置文件,但仍需在 hibernate.cfg.xml 配置文件中进行实体类的注册

实例:class班级、student学生、project学科。

 配置一对多与多对一、多对多。

学生实体类 Student.java

package com.pojo;

import java.util.Date;
import java.util.Set; import javax.persistence.CascadeType;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="student_info",schema="C##java06")
public class Student {
@Id//表明这个字段就是主键
@GeneratedValue(generator="incre")
@GenericGenerator(name="incre",strategy="increment")
@Column(name="student_id")
int studentId; @Column(name="student_name")
String studentName; @Column(name="student_Sex")
String studentSex;
@Column(name="student_age")
int studentAge;
// @Column(name="class_Id")
// int classId;
@ManyToOne(cascade=CascadeType.REFRESH,fetch=FetchType.EAGER)
@JoinColumn(name="class_id")
ClassInfo classinfo;
@Column(name="birthday")
Date birthday;
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="stu_project")
Set<ProjectInfo> projects; public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentSex() {
return studentSex;
}
public void setStudentSex(String studentSex) {
this.studentSex = studentSex;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
// public int getClassId() {
// return classId;
// }
// public void setClassId(int classId) {
// this.classId = classId;
// }
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
} public ClassInfo getClassinfo() {
return classinfo;
} public void setClassinfo(ClassInfo classinfo) {
this.classinfo = classinfo;
} public Set<ProjectInfo> getProjects() {
return projects;
} public void setProjects(Set<ProjectInfo> projects) {
this.projects = projects;
} public Student() {
} public Student(int studentId, String studentName, String studentSex, int studentAge, ClassInfo classinfo, Date birthday) {
this.studentId = studentId;
this.studentName = studentName;
this.studentSex = studentSex;
this.studentAge = studentAge;
// this.classId = classId;
this.classinfo = classinfo;
this.birthday = birthday;
} }

班级实体类ClassInfo.java

package com.pojo;

import java.util.Date;
import java.util.Set; import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name="class_info",schema="JAVA")
public class ClassInfo {
@Id//表明这个字段就是主键
@GeneratedValue(generator="incre")
@GenericGenerator(name="incre",strategy="increment")
@Column(name="class_id")
// @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CUST_SEQ")//使用序列的方式维护主键
int classId; @Column(name="class_name")
String className; @Column(name="create_time")
Date createTime; @Column(name="status")
String status; @OneToMany(mappedBy="classinfo",cascade=CascadeType.ALL ,fetch=FetchType.EAGER)
Set<Student> stus; public ClassInfo() {
} public ClassInfo(int classId, String className, Date createTime, String status) {
this.classId = classId;
this.className = className;
this.createTime = createTime;
this.status = status;
} public int getClassId() {
return classId;
}
public void setClassId(int classId) {
this.classId = classId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
} public Set<Student> getStus() {
return stus;
} public void setStus(Set<Student> stus) {
this.stus = stus;
} }

科目实体类ProjectInfo.java

package com.pojo;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name="project_info",schema="JAVA")
public class ProjectInfo {
@Id//表明这个字段就是主键
@GeneratedValue(generator="incre")
@GenericGenerator(name="incre",strategy="increment")
@Column(name="project_id")
int projectid; @Column(name="project_name")
String projectname; @ManyToMany(mappedBy="projects")
Set<Student> stus; public int getProjectid() {
return projectid;
}
public void setProjectid(int projectid) {
this.projectid = projectid;
}
public String getProjectname() {
return projectname;
}
public void setProjectname(String projectname) {
this.projectname = projectname;
} }

 配置文件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="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.username">C##java06</property>
<property name="connection.password">java123</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 所有的实体类映射文件要在此处全部注册 -->
<!-- <mapping resource="com/pojo/Student.hbm.xml"/> -->
<!-- 用注解的方式写pojo -->
<mapping class="com.pojo.ClassInfo"/>
<mapping class="com.pojo.Student"/>
<mapping class="com.pojo.ProjectInfo"/>
</session-factory>
</hibernate-configuration>

测试代码

TestRelotion.java
package com.dao;

import java.util.Date;
import java.util.HashSet;
import java.util.List; import com.pojo.ClassInfo;
import com.pojo.ProjectInfo;
import com.pojo.Student; public class TestRelotion {
public static void main(String[] args) {
IStudentDAO stuDAO = new StudentDAO();
// List<Student> list = stuDAO.queryObjectByHql("from Student");
// for (Student stu : list) {
// System.out.println(stu.getStudentName()+",班级是:"+stu.getClassinfo().getClassName()+"开班时间:"+stu.getClassinfo().getCreateTime());
// }
//
IClassInfoDAO cdao = new ClassInfoDAO();
// List<ClassInfo> cs = cdao.queryObjectBySql("select * from Class_Info a where a.class_Id=1",ClassInfo.class);
// ClassInfo c= cs.get(0);
// System.out.println(c.getClassName());
// for (Student stu : c.getStus()) {
// System.out.println(stu.getStudentName()+"\t"+stu.getBirthday());
// } //新增学员
// ClassInfo c = new ClassInfo(2, null, null, null);
// Student stu = new Student(0,"测试新增","1",20,c,new Date());
// stuDAO.saveObject(stu); //删除学员
// Student stu = new Student();
// stu.setStudentId(13);
// stuDAO.delObject(stu); //修改学员
// List<Student> stus = stuDAO.queryObjectByHql("from Student a where a.studentId=1");
// Student stu = stus.get(0);
// stu.setStudentName("谢娜");
// stu.setClassinfo(new ClassInfo(1,null,null,null));
// stuDAO.updateObject(stu); //删除班级
// ClassInfo c = new ClassInfo(3, null, null, null);
// cdao.delObject(c); //给学员选课
//给学员新增选课
//给学员删除选课
//查询学员选了哪些课
//查询课程被哪些学员选中
List<Student> stus = stuDAO.queryObjectByHql("from Student a where a.studentId=1");
Student stu = stus.get(0);
//stu.setProjects(projects); IProjectInfoDAO projectDAO = new ProjectInfoDAO();
// List<ProjectInfo> plist = projectDAO.queryObjectByHql("from ProjectInfo");
// stu.setProjects(new HashSet(plist));
// stuDAO.updateObject(stu); // for (ProjectInfo p : stu.getProjects()) {
// System.out.println(p.getProjectname());
// }
}
}

附:

  常用JPA注解

常用:
@Entity: @Table(name="表名",schema="数据库名"):表明这是一个实体类。一般用于jpa这两个注解一般一块使用,但是如果表名和实体类名相同的话, @Table可以省略 @Id:表示该属性为主键。 @Column:如果字段名与列名相同,则可以省略。 @GeneratedValue:JPA通用策略生成器
(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):表示主键生成策略是sequence(可以为Auto、IDENTITY、native等,Auto表示可在多个数据库间切换),指定sequence的名字是repair_seq。
TABLE:使用一个特定的数据库表格来保存主键。
SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。
IDENTITY:主键由数据库自动生成(主要是自动增长型)
AUTO:主键由程序控制。 @GenericGenerator:hibernate主键策略生成器
@GenericGenerator注解配合 @GeneratedValue一起使用, @GeneratedValue注解中的"generator"属性要与 @GenericGenerator注解中name属性一致,strategy属性表示hibernate的主键生成策略 @OneToOne、 @OneToMany、 @ManyToOne:对应hibernate配置文件中的一对一,一对多,多对一,有主从关系。
eg: @OneToMany(mappedBy="classinfo",cascade=CascadeType.ALL ,fetch=FetchType.EAGER)
fetch取值:
FetchType.EAGER 表示主类被加载时加载,
FetchType.LAZY 后者表示被访问时才会加载。
cascade取值:
CascadeType.PERSIST(级联新建),
CascadeType.REMOVE(级联删除),
CascadeType.REFRESH(级联刷新),
CascadeType.MERGE(级联更新),
CascadeType.ALL(选择全部)。 @JoinColumn(name=”loginId”):一对一:本表中指向另一个表的外键。一对多:另一个表指向本表的外键。 其他:
@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name为sequence的名称,以便使用,sequenceName为数据库的sequence名称,两个名称可以一致。 @Transient:表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。
如果一个属性并非数据库表的字段映射,就务必将其标示为 @Transient,否则,ORM框架默认其注解为 @Basic。
@Basic(fetch=FetchType.LAZY):标记可以指定实体属性的加载方式 @JsonIgnore:作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响。 @MappedSuperClass:用在确定是父类的entity上。父类的属性子类可以继承。 @NoRepositoryBean:一般用作父类的repository,有这个注解,spring不会去实例化该repository。