1-Hibernate-Common Concepts

Hibernate

Entity class writing rules

(1) The entity class is required to have an attribute as a unique value (id)
(2) The entity class attribute uses a wrapper class
- the student has an attribute as a score, and the Integer can be null, indicating that the student did not take the test

Primary key generation strategy

<id name="id" column="id">
    <!-- 设置数据库表id增长策略
        native:生成表的id自增长
     -->
    <generator class="native"></generator>
</id>

The generator tag class attribute:

  • Increment: used for long, short, int, the unique identifier is automatically generated by hibernate in an incremental manner, each increment is 1
  • identity: use the primary key provided by the underlying database itself to generate identifiers, mainly used in MySQL, DB2, SQLServer, requires the database to define the primary key as self-increasing
  • sequence: used for Oracle, hibernate generates identifiers based on the underlying database sequence, requiring the database to support sequences
  • native: select the corresponding generation strategy according to the underlying database
  • uuid: use the uuid generation strategy, the entity class id attribute must be a string

crud operation

1. Insert

        // 5 insert操作
        User user = new User();
        user.setUsername("root");
        user.setPassword("root");

2. session.save(user);Select

        /*
         * 5 执行查询操作
         * 调用session的get方法
         * 第一个参数:实体类的class
         * 第二个参数:id值
         */
        User user = session.get(User.class, 1);
        System.out.println(user);

3. Update

        //5 执行修改操作
        //5.1 根据id查询
        User user = session.get(User.class, 1);
        //5.2 set方法设置
        user.setPassword("123");
        //5.3 调用session的update方法修改(底层通过id来进行修改)
        session.update(user);

4. Delete

        //5 执行删除操作
        //第一种 :根据id查询对象,调用session对象delete方法
        User user = session.get(User.class, 2);
        session.delete(user);
        //第二种:
        User user2 = new User();
        user2.setId(3);
        session.delete(user2);

Hibernate cache

1. Cache:

The data is stored in the database, and the database itself is a file system, and the data is accessed in a stream manner, which is inefficient.
By storing the data in the memory, the data can be directly read in the memory without using the stream method, which is highly efficient.

2. Hibernate first level cache

(1) Hibernate first-level cache is opened by default
(2) Use scope: session scope, from session creation to session closing
(3) Store data persistent data

3. Hibernate second level cache

(1) Rarely used, redis replaces
(2) Scope: SessionFactory scope

Hibernate native thread binding session

(1) Configure in the core configuration file

<!-- 本地线程绑定Session -->
<property name="hibernate.current_session_context_class">thread</property>

(2) Call the method in SessionFactory

public static Session getSession() {
    return SESSION_FACTORY.getCurrentSession();
}

Hibernate API

1. Query object

The parameter is the hql statement

            //创建Query对象
            Query query = session.createQuery("from User");
            //调用query对象里的list方法得到结果
            List<User> list = query.list();

2. Criteria object

The parameter is the entity class.class

            //创建criteria对象
            Criteria criteria = session.createCriteria(User.class);
            //调用criteria对象里的list方法得到结果
            List<User> list = criteria.list();

3. SQLQuery object

Hibernate one-to-many operation (one-to-many relationship between two tables through foreign keys)

1. One-to-many mapping configuration

Take the student class as an example: one student corresponds to one class, and one class corresponds to multiple students
(1) Create student and class entity classes, and establish connections
Student class:

//一个学生对应一个班级
    private Classs classs;
    public Classs getClasss() {
        return classs;
    }
    public void setClasss(Classs classs) {
        this.classs = classs;
    }

class class:

//一个班级对应多个学生
    private Set<Student> students = new HashSet<>();
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }

(2) Configuration mapping file
Student mapping file

<class name="com.wzw.hibernate.model.Student" table="student">
        <id name="sId" column="sid">
            <generator class="native"></generator>
        </id>
        <property name="sName" column="sname"></property>
        <property name="sAge" column="sage"></property>
        <!-- 表示学生所属的班级 
            name属性:班级实体类的classs对象名称
            class属性:Classs全路径
            column属性:外键名称
        -->
        <many-to-one name="classs" class="com.wzw.hibernate.model.Classs" column="cid"></many-to-one>
    </class>

class map file

<class name="com.wzw.hibernate.model.Classs" table="class">
        <id name="cId" column="cid">
            <generator class="native"></generator>
        </id>
        <property name="cName" column="cname"></property>
        <!-- 在班级类映射文件中,表示班级所拥有的全部学生
            set标签:
            name属性:在班级实体类中表示学生的set集合名称
         -->
        <set name="students">
            <!-- 一对多建表,有外键
                hibernate:双向维护外键,既一和多双方都要配置
             -->
             <key column="sid"></key>
             <!-- 班级的所有学生,class里写学生的全路径-->
             <one-to-many class="com.wzw.hibernate.model.Student"/>
        </set>
    </class>

(3) Create a core configuration file and introduce the mapping file into the core configuration file

<!-- hibernate自动创建表
            update:如果已经有表,更新;如果没有,创建
         -->
        <property name="hibernate.hbm2ddl.auto">update</property> 
        <!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
        <!-- 配置数据库方言
            在MySQL里实现分页关键字 limit,只能在MySQL里使用
            在Oracle中,rownum
            让hibernate框架识别不同数据库的语句
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 3 把映射文件放到核心配置文件中 -->
        <mapping resource="com/wzw/hibernate/model/Classs.hbm.xml"/>
        <mapping resource="com/wzw/hibernate/model/Student.hbm.xml"/>

2. One-to-many cascade save

            // 添加
            // 1 创建学生对象与班级对象
            Student student = new Student();
            student.setsName("wzw");
            student.setsAge(16);

            Classs classs = new Classs();
            classs.setcName("104班");
            //2 建立学生与班级间联系
            student.setClasss(classs);
            classs.getStudents().add(student);
            //3 insert
            session.save(classs);
            session.save(student);

3. One-to-many cascade delete

(1) Get the id of the class to be deleted
(2) Get the class student according to the class id
(3) Delete the student
(4) Delete the class

Hibernate many-to-many operation (a many-to-many relationship is established between two tables through a third table)

One user corresponds to multiple roles, and one role corresponds to multiple users

1. Many-to-many mapping configuration

(1) Create user and role entity classes, and establish contacts
User class:

    //一个用户对应多个角色
    private Set<Role> roles = new HashSet<>();
    public Set<Role> getRoles() {
        return roles;
    }
    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

Character class:

    //一个角色对应多个用户
    private Set<User> users = new HashSet<>();  
    public Set<User> getUsers() {
        return users;
    }
    public void setUsers(Set<User> users) {
        this.users = users;
    }

(2) Configure the mapping file
User:

<!-- name:Set<Role> roles
        table:第三张表名称
-->
<set name="roles" table="user_role">
<!-- key标签column属性:配置当前的映射文件user在第三张表中外键的名称user_id -->
    <key column="user_id"></key>
        <!-- class:Role全路径
            column:Role在第三张表中外键的名称role_id
        -->
    <many-to-many class="com.wzw.hibernate.model.Role" column="role_id"></many-to-many>
</set>

Role:

<set name="users" table="user_role">
    <key column="role_id"></key>
    <many-to-many class="com.wzw.hibernate.model.User" column="user_id"></many-to-many>
</set>

(3) Create a core configuration file and introduce the mapping file into the configuration file

        <!-- 3 把映射文件放到核心配置文件中 -->
        <mapping resource="com/wzw/hibernate/model/User.hbm.xml"/>
        <mapping resource="com/wzw/hibernate/model/Role.hbm.xml"/>

2. Many-to-many cascade save

Role.hbm.xml:

<set name="users" table="user_role" cascade="save-update">

User.hbm.xml:

<set name="roles" table="user_role" cascade="save-update">
            //级联保存
            //1 创建用户与角色对象
            User user1 = new User();
            User user2 = new User();
            user1.setUsername("zhangsan");
            user1.setPassword("123");
            user2.setUsername("lisi");
            user2.setPassword("123");

            Role role1 = new Role();
            Role role2 = new Role();
            Role role3 = new Role();
            role1.setRole_name("root");
            role2.setRole_name("S");
            role3.setRole_name("A");

            //2 User与Role建立联系
            //user1--role1/role2
            //user2--role2/role3
            user1.getRoles().add(role1);
            user2.getRoles().add(role2);
            user2.getRoles().add(role2);
            user2.getRoles().add(role3);

            //3 添加
            session.save(user1);
            session.save(user2);

3. Many-to-many cascade delete

HIbernate query method

1. Object Navigation Query

Query the A object according to the id, and then query the B object (Set ) in A

2. OID query

Query a record based on id and return the object

3. hql query

Query object, hql statement

4. QBC query

Criteria object

5. Local sql query

SQLQuery object, sql statement

(Lazy Loading) Hibernate Retrieval Strategy

1. Hibernate retrieval strategies are divided into two categories:

get() Immediate query: query
according to id, call the get method, and send a query statement to query the database immediately after calling the get method
load() Delay query: query
according to the id, call the load method, the query statement will not be sent to query the database immediately, only the object will be obtained The statement query will only be sent when the value inside

2. Delayed query is divided into two categories

Class-level delay The entity class object is returned
according to the id query. Calling the load method will not send the statement immediately.
Association-level delay
First query A, and then query all B in A, and whether this process needs to be delayed, this process is called association-level delay

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324678719&siteId=291194637