Annotated Association of hibernate

Posted by phpshift on Mon, 03 Jan 2022 18:13:44 +0100

1, Use annotations for associations

  user configuration table

<mapping resource="org/zttc/itat/model/User.hbm.xml"/>
<mapping class="org.zttc.itat.model.User"/>

It replaces the original xml

Class level annotation

@The entity annotation declares a class as an entity Bean. Entity must have @ Id. You can generate a Table without adding @ Table. Name is the Table name

@Table(name="tbl_sky")

   name table name, which can be omitted
  schema schema
  catalog directory
@Write only one Entity and @ Table, which will affect hql, so it is recommended to write them all

Database system – > catalog -- > Schema -- > tables, views, fields

However, different database manufacturers support them differently

The schema of MySQL represents the database name, which is not supported by catalog

The schema of Oracle represents the user ID, which is not supported by catalog

Attribute level annotation

It can be placed on properties or get methods

@The ID annotation declares the ID identifier of the entity Bean.

Note: if multiple attributes define a primary key, the Serializable interface must be implemented

The length of the string as the primary key must be limited, otherwise no error will be reported during execution, and there is no table in the database

@GeneratedValue

  strategy = GenerationType.AUTO specifies the default AUTO for the primary key generation policy

  GenerationType.IDENTITY: proxy primary key, which is suitable for dbms supporting self increment such as Mysql or ms sql server. The primary key value is not maintained by hibernate.

  GenerationType.SEQUENCE: proxy primary key, which is suitable for dbms supporting sequence such as oracle. The primary key value is not maintained by hibernate, but generated by sequence.

  GenerationType.TABLE: use tables to manage primary keys

Common primary key policies

Manual assignment strategy

@Id
@GeneratedValue(generator = "sid")
@GenericGenerator(name = "sid", strategy = "assigned")

Table strategy

@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="my_table")
@TableGenerator(
    name = "my_table",    
    allocationSize = 1  // Growth value
)

Database uuid policy

@Id
@GenericGenerator(name = "my-uuid", strategy = "uuid")
@GeneratedValue(generator = "my-uuid")

General field
@Column(name="name_t")

name=“columnName”; Listing
boolean unique() default false; Set unique constraint on this column
boolean nullable() default true; Column can be empty?
boolean insertable() default true; Whether the column is used as a column for generating the insert statement
boolean updatable() default true; Whether the column is used as a column for generating the update statement
String columnDefinition() default""; Default value
String table() default “”; Define the corresponding table (default is the main table)
int length() default 255; Column length
int precision() default 0;
Decimalprecision
int scale() default 0;
decimal scale decimal length

columnDefinition

Usage 1: @ Column(name = "Email", columnDefinition = "varchar(128) not null")

Usage 2: @ Column(name = "Remark", columnDefinition = "text") large text format

@Transient persistence ignores the field associated mapping annotation

2, Multi table cascade

  bidirectional one to many is the most commonly used cascade relationship

@Entity
@Table(name="tb_student")
public class Student {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    private String no;
    @ManyToOne(fetch= FetchType.LAZY)
    @JoinColumn(name="cid")
    private Classroom classroom;
}

@Entity
@Table(name="tb_classroom")
public class Classroom {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    @OneToMany(mappedBy="classroom")    
    private Set<Student> students;
}

@JoinColumn(name = "cid") the name of the foreign key added to the current entity table is cid

mappedBy = "classroom" the relationship is not maintained by the current attribute, but by the classroom attribute of the object in the collection

one-on-one

One to one is similar to nested classes, which are less used. Most settings are similar to one to many

@Entity
@Table(name="tb_person")
public class Person {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    @OneToOne(mappedBy = "person")
    private IDCard idCard;
}
@Entity
@Table(name="tb_idCard")
public class IDCard {
    @Id
    @GeneratedValue
    private int id;
    private String no;
    @OneToOne
    @JoinColumn(name="pid")
    private Person person;
}

Many to many

Two way many to many relationship, roles and resources (relationship between students and courses), the focus is the middle table

@Entity
@Table(name = "tb_role")
public class Role {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    @ManyToMany(mappedBy="roles")
    private Set<Resource > resources;
}

@Entity
@Table(name = "tb_resource")
public class Resource {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    @ManyToMany
    @JoinTable(name="tb_role_resource",joinColumns={@JoinColumn(name="re_id")},
            inverseJoinColumns={@JoinColumn(name="ro_id")})
    private Set<Role> roles;
}

joinColumns the name of the primary key of the current class in the intermediate table

The id of the opposite table of inverseJoinColumns is the name of the current intermediate table

Cascade relation of cascade
  CascadeType.PERSIST: cascade addition (also known as cascade saving): when saving the order object, the objects in items will also be saved. Press method corresponding to EntityManager
  CascadeType.MERGE: level Union (cascade update): if the items attribute is modified, the objects in items are modified when the order object is saved. merge method corresponding to EntityManager
  CascadeType.REMOVE: cascade deletion: deleting the order object will also delete the objects in items. remove method corresponding to EntityManager
  CascadeType.REFRESH: cascade refresh: get the object in the order object and retrieve the latest items at the same time. The refresh(object) method of the corresponding EntityManager is valid. The latest data in the database will be queried again (less used)
  CascadeType.ALL: the above four are

fetch = FetchType.EAGER
  LAZY negative
  EAGER positive

@LazyCollection( value = LazyCollectionOption.EXTRA)
   TRUE (the collection is delayed and can only be loaded when accessed),
   EXTRA (the collection is delayed, and all operations will try to avoid loading the collection. It is particularly useful for a huge collection, because it is not necessary to load all the elements in such a collection)
   false (Association of non delayed loading)

Topics: Java Database Hibernate