Hibernate配置(通过注解配置)

Posted 南橘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate配置(通过注解配置)相关的知识,希望对你有一定的参考价值。

本文主要讲通过注解配置来替换Hibernate的映射文件


1.多对一配置

package com.jazz7.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

// 1.注册bean
@Entity
// 2.和数据库表进行关联,如果名字不同的话,需要在这里指定name
@Table
public class Emp {
    // 3.配置id
    @Id
    //4.配置主键生成策略
    @GeneratedValue(generator="empgener",strategy=GenerationType.SEQUENCE)
    //配置序列
    @SequenceGenerator(name="empgener",sequenceName="seq_emp_id",allocationSize=1,initialValue=1)
    private int empno;
    private String ename;
    private String job;
    private Integer mgr;    
    private Date hiredate;
    private float sal;
    private Float comm;
    //多对一关联
    @ManyToOne(targetEntity=Dept.class)
    //配置外键
    @JoinColumn(name="deptno")
    private Dept dept;
    // ......省略get()set()
}

2.一对多配置

@Entity
@Table
public class Dept {
    @Id
    @Column
    private int deptno;
    private String dname;
    private String loc;
    
    //一对多配置
    @OneToMany(mappedBy="dept")
    private Set<Emp> emps;
    // ...省略get()set()
}

 

3.多对多配置

@Entity
@Table(name = "tbl_student")
public class Student {
    @Id
    @Column
    @GeneratedValue(generator = "stname", strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name = "stname", sequenceName = "seq_student_id", allocationSize = 1, initialValue = 1)
    private int sid;
    private String sname;
    // 多对多配置
    @ManyToMany(targetEntity=Teacher.class,mappedBy="students")
    //配置“关系表”,joinColumns是“本类”在关系表中的外键,inverseJoinColumns是相关联类在关系表中的外键
    @JoinTable(name = "tbl_teacher_student",  joinColumns ={@JoinColumn(columnDefinition="sid")},  inverseJoinColumns = {@JoinColumn(columnDefinition="tid")})
    private Set<Teacher> teachers;
    // ...省略get()set()
}

 

以上是关于Hibernate配置(通过注解配置)的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot @Value注解中文配置乱码

hibernate关联映射注解

hibernate关于一对一注解配置

Hibernate注解配置

hibernate笔记--使用注解(annotation)方式配置单(双)向多对一的映射关系

Hibernate框架学习之注解配置关系映射