当前位置:网站首页>Hibernate learning 2 - lazy loading (delayed loading), dynamic SQL parameters, caching

Hibernate learning 2 - lazy loading (delayed loading), dynamic SQL parameters, caching

2022-06-24 23:52:00 Uh huh**

Lazy loading == Lazy loading is enabled by default

summary

Lazy loading : When Bean Object sets cascading queries at the code level, that is One to many 、 Many to many 、 Many to one relationship , Query a Bean when , Not sending two SQL, Instead, just send one SQL, When the code needs to access the Bean Cascading data , Get cascading data before sending SQL.

Code == lazy Property value

one-to-many label

summary

lazy Property value
1. true: The default value is , Turn on lazy loading
1. false: Turn off lazy loading
1. extra: More intelligent lazy loading

true/false

SysUser.java

@Getter
@Setter
public class SysUser extends BaseEntity {
    
    private static final long serialVersionUID = 2095940921263481761L;

    Set<Article> articles;

    /**  The user nickname  -  If you do not set a nickname, you can directly use the account name to display  */
    private String nickName;

    /**  Head picture address  */
    private String headUrl;

    /**  Account  */
    private String loginName;

    /**  password  */
    private String password;

    /**  cell-phone number  */
    private String phoneNumber;

    /**  mailbox  */
    private String email;

    /**  Gender  */
    private Integer gender;

    /**  Individuality signature  */
    private String personalMotto;


    /**  Last login time  -  Format  - yyyyMMddHHmmss */
    private String lastLoginTime;

    /**  The login status :0 Not logged in  1 Single device login  2 Multi device login  */
    private Integer loginStatus;

    /**  Account disabled status :0 The account can use  1 The account is not available ( Title ) */
    private Integer disabledStatus;

    @Override
    public String toString() {
    
        return "SysUser{" +
                "nickName='" + nickName + '\'' +
                ", headUrl='" + headUrl + '\'' +
                ", loginName='" + loginName + '\'' +
                ", password='" + password + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                ", personalMotto='" + personalMotto + '\'' +
                ", lastLoginTime='" + lastLoginTime + '\'' +
                ", loginStatus=" + loginStatus +
                ", disabledStatus=" + disabledStatus +
                '}';
    }
}


Article.java

@NoArgsConstructor
@AllArgsConstructor
@Builder
@Accessors(chain = true)
@Data
public class Article extends BaseEntity {
    

    private static final long serialVersionUID = -4714261187453073302L;


    private SysUser sysUser;

    /**  Article title  */
    private String title;

    /**  Article content  */
    private String content;

    private String abbreviationContent;

    /**  Number of times the article has been viewed  */
    private Integer checkNum;

    /**  The number of likes of the current article  */
    private Integer likeNum;

    /**  The current article doesn't like counting  */
    private Integer notLikeNum;

    /**  Whether the article violates the rules :0 No violation  1 Violations,  -  Violations cannot be displayed  */
    private Integer isViolation;

    /**  The creator  -  Redundant fields  - user Tabular nickName */
    private String createBy;

    /** The picture of the list article shows  -  If specified, use the specified picture ( Function not done ), If not specified, the first picture of the article will be used , If there is no icon in the article, use the image of directory splitting */
    private String imgUrl;

    /** Inside the article */
    private String imgUrls;

    /** Article content type :1 Rich text  2Markdown 3 leave a blank */
    private String type;

    /** Article state ;-1 Violations,  0 draft  1 Published and made public  2 Published and private */
    private String status;

}


SysUser.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="top.linruchang.entity.SysUser" table="sys_user">
        <id name="id" type="java.lang.String">
            <column name="id"></column>
            <!-- Insertion time , If you don't have settings ID, Will help you automatically add ID-->
            <generator class="uuid"></generator>
        </id>


        <property name="headUrl" type="java.lang.String">
            <column name="head_url" ></column>
        </property>

        <property name="loginName" type="java.lang.String">
            <column name="login_name" ></column>
        </property>

		<!-- The default is to enable lazy loading , Switch to check the effect when testing -->
        <set name="articles" table="article" lazy="false">
            <key column="user_id"></key>
            <one-to-many class="top.linruchang.entity.Article"></one-to-many>
        </set>

    </class>
</hibernate-mapping>


Article.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="top.linruchang.entity.Article" table="article">
        <id name="id" type="java.lang.String">
            <column name="id" ></column>
            <!-- Insertion time , If you don't have settings ID, Will help you automatically add ID-->
            <generator class="uuid"></generator>
        </id>

        <!--<property name="userId" type="java.lang.String">-->
        <!-- <column name="user_id"></column>-->
        <!--</property>-->


        <property name="title" type="java.lang.String">
            <column name="title"></column>
        </property>

        <property name="content" type="java.lang.String">
            <column name="content"></column>
        </property>


        <property name="likeNum" type="java.lang.Integer">
            <column name="like_num"></column>
        </property>

        <!-- The default is to enable lazy loading , Switch to check the effect when testing , If it shows lazy=true May be an error -->
        <many-to-one lazy="false" name="sysUser" column="user_id" class="top.linruchang.entity.SysUser" />

    </class>
</hibernate-mapping>


MyTest2.java

public class MyTest2 {

    @SneakyThrows
    public static void main(String[] args) {

        new Thread(() -> {
            Configuration configure = new Configuration().configure();

            // obtain sessionFactory
            SessionFactory sessionFactory = configure.buildSessionFactory();
            // Get database connection session
            Session session = sessionFactory.openSession();
            SysUser sysUser = session.find(SysUser.class, "6d72c93aa292cf2ca2e789919a5e7bdc");

            System.out.println(sysUser);
        }).start();

        Thread.sleep(10000);

    }

}

 Insert picture description here

 Insert picture description here

extra

Than true/fasle Attribute is a more lazy way to load , Or it can be said that a more intelligent loading method , If you only need the length of the set ,hibernate Will check count Instead of looking at the entire data set , When you use data , Look up the data set in the meeting *


SysUser.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="top.linruchang.entity.SysUser" table="sys_user">
        <id name="id" type="java.lang.String">
            <column name="id"></column>
            <!-- Insertion time , If you don't have settings ID, Will help you automatically add ID-->
            <generator class="uuid"></generator>
        </id>


        <property name="headUrl" type="java.lang.String">
            <column name="head_url" ></column>
        </property>

        <property name="loginName" type="java.lang.String">
            <column name="login_name" ></column>
        </property>

        <!-- The more lazy loading mode turns on -->
        <set name="articles" table="article" lazy="extra">
            <key column="user_id"></key>
            <one-to-many class="top.linruchang.entity.Article"></one-to-many>
        </set>

    </class>
</hibernate-mapping>


test

    @Test
    public void test6() throws InterruptedException {
    

        Configuration configure = new Configuration().configure();

        // obtain sessionFactory
        SessionFactory sessionFactory = configure.buildSessionFactory();
        // Get database connection session
        Session session = sessionFactory.openSession();
        SysUser sysUser = session.find(SysUser.class, "6d72c93aa292cf2ca2e789919a5e7bdc");

        System.out.println(sysUser.getArticles().size());

        System.out.println("============================");

        System.out.println(sysUser.getArticles());
        
    }

 Insert picture description here

many-to-one label

summary

lazy Property value
false: Turn off lazy loading
proxy: agent , Lazy load mode . Call the method to access one Variable , It's all about sending SQL Statement query one The object of
no-proxy: Not acting for , Lazy load mode , Whether the calling method accesses one Variable , It's all about sending SQL Inquire about one object
Choose either of the two , No big problem , I don't understand the difference
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="top.linruchang.entity.Article" table="article">
        <id name="id" type="java.lang.String">
            <column name="id" ></column>
            <!-- Insertion time , If you don't have settings ID, Will help you automatically add ID-->
            <generator class="uuid"></generator>
        </id>

        <!--<property name="userId" type="java.lang.String">-->
        <!-- <column name="user_id"></column>-->
        <!--</property>-->


        <property name="title" type="java.lang.String">
            <column name="title"></column>
        </property>

        <property name="content" type="java.lang.String">
            <column name="content"></column>
        </property>


        <property name="likeNum" type="java.lang.Integer">
            <column name="like_num"></column>
        </property>
        
        <!--  Adjust this attribute by yourself , By default, the lazy load mode is enabled  --> 
        <many-to-one lazy="no-proxy" name="sysUser" column="user_id" class="top.linruchang.entity.SysUser" />

    </class>
</hibernate-mapping>

many-to-many label == Follow one-to-many equally

summary

lazy Property value
1. true: The default value is , Turn on lazy loading
1. false: Turn off lazy loading
1. extra: More intelligent lazy loading
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="top.linruchang.entity.MyOrder2" table="my_order">
        <id name="id" type="java.lang.String">
            <column name="id"></column>
            <!-- Insertion time , If you don't have settings ID, Will help you automatically add ID-->
            <generator class="uuid"></generator>
        </id>

        <property name="name" type="java.lang.String">
            <column name="name"></column>
        </property>


        <property name="money" type="java.lang.String">
            <column name="money"></column>
        </property>

        <!--  Here you can set lazy loading -->
        <set name="myUser2" table="user_order_rel" lazy="extra">
            <key column="my_order_id" ></key>
            <many-to-many column="my_user_id" class="top.linruchang.entity.MyUser2"></many-to-many>
        </set>
    </class>
</hibernate-mapping>

dynamic SQL Parameters = Not on by default

 Insert picture description here

insert = Follow MyBatisPlus equally , If the attribute field is empty, the field will not appear in SQL in

update = Follow MyBatisPlus Dissimilarity , Determine whether the attribute field needs to appear in... According to the cached object SQL in , If the attribute field cache value is inconsistent with the current object, it appears in SQL, Otherwise, it will not appear


Article.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!-- package: similar mybatis Of Bean Alias type-aliases-package This attribute , Used for some attributes without writing fully qualified names -->
<!-- default-lazy: Lazy loading is enabled by default , One to many , Many to many , Use on many to one relationships -->
<!-- auto-import: Default true, Whether the partially qualified name can be used in the query statement , If there are two projects with the same name Bean, It is best to set to... In both mapping files false-->
<hibernate-mapping package="top.linruchang.entity" default-lazy="true" auto-import="false" >

    <!-- dynamic-insert dynamic-update: The default is false.true Similar to  mybatisplus Code insert for Java sentence , As long as the attribute is empty update、insert Of SQL Statement, the column will not appear  -->
    <class name="Article" table="article" dynamic-insert="true" dynamic-update="true">
        <id name="id" type="java.lang.String">
            <column name="id" ></column>
            <!-- Insertion time , If you don't have settings ID, Will help you automatically add ID-->
            <generator class="uuid"></generator>
        </id>

        <!--<property name="userId" type="java.lang.String">-->
        <!-- <column name="user_id"></column>-->
        <!--</property>-->


        <property name="title" type="java.lang.String">
            <column name="title"></column>
        </property>

        <property name="content" type="java.lang.String">
            <column name="content"></column>
        </property>


        <property name="likeNum" type="java.lang.Integer">
            <column name="like_num"></column>
        </property>

        <many-to-one lazy="no-proxy" name="sysUser" column="user_id" class="SysUser" />

    </class>
</hibernate-mapping>


The test program

    @Test
    public void test6() {
    

        Configuration configure = new Configuration().configure();
        SessionFactory sessionFactory = configure.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

        // The results will be session cache 
        Article article = session.find(Article.class, "4028b88178e54c750178e54c77c80000");
        System.out.println(article);

        //  dynamic update=true Under the circumstances : Compare the above cache with the current object 
        article.setTitle(" Put them on the sofa to identify each other ==");
        session.saveOrUpdate(article);
        
        // If you use this , Final meeting save Of , Because it is necessary to judge whether insert、update It is based on the cache 
        // Article updateArticle = new Article();
        // updateArticle.setId(article.getId())
        // updateArticle.setContent("fdsfdsfsd");
       // session.saveOrUpdate(updateArticle);

        transaction.commit();
        session.close();

    }


Dynamic update is not turned on SQL
 Insert picture description here


Turn on dynamic updates SQL
 Insert picture description here

cache

First level cache Session Level = Default on

    @Test
    public void test6() {
    

        Configuration configure = new Configuration().configure();
        SessionFactory sessionFactory = configure.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        
        
        Article article = session.find(Article.class, "4028b88178e54c750178e54c77c80000");
        System.out.println(article);
        Article article2 = session.find(Article.class, "4028b88178e54c750178e54c77c80000");
        System.out.println(article2);

        transaction.commit();
        session.close();

    }

 Insert picture description here

原网站

版权声明
本文为[Uh huh**]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241844461389.html