当前位置:网站首页>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**】
List of articles
- Lazy loading == Lazy loading is enabled by default
- dynamic SQL Parameters = Not on by default
- 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
- cache
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
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);
}
}


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());
}

many-to-one label
summary
<?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
<?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 = 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
Turn on dynamic updates SQL
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();
}

边栏推荐
- Hello C (IV) -- pointer and function
- Is there really something wrong with my behavior?
- 都2022年了,你还不了解什么是性能测试?
- Quickly build KVM virtual machine on # yyds dry goods inventory # physical machine
- Using ADC to control brushless motor source program STM32 library function
- HMS core discovery Episode 13 live broadcast Preview - building the real world in mobile games
- 7-7 solving mode problems
- Global and Chinese 3-Chlorobenzaldehyde industry operation mode and future development trend report 2022 ~ 2028
- Ultra vires vulnerability & Logic vulnerability (hot) (VIII)
- Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
猜你喜欢

Canvas spiral style animation JS special effect

Installing IBM CPLEX academic edition | CONDA installing CPLEX

Spark's wide dependence and narrow dependence yyds dry goods inventory

磁带svg动画js特效

颜色渐变梯度颜色集合

Morris traverse

Tremblement de terre réel ~ projet associé unicloud

Hibernate学习2 - 懒加载(延迟加载)、动态SQL参数、缓存
HMS core discovery Episode 13 live broadcast Preview - building the real world in mobile games

Nacos究竟是什么
随机推荐
Inventory of data governance status of six major banks: governance architecture, data standards and data middle office (April 2022)
Volcano becomes spark default batch scheduler
Arbitrary file download of file operation vulnerability (7)
MySQL semi sync replication
canvas螺旋样式的动画js特效
当初吃土建起来的“中台”,现在为啥不香了?
抖音实战~实现App端视频上传与发布
抖音实战~发布短视频流程梳理
(Smooth)ScrollToPosition doesn't work properly with RecyclerView
ArcGIS loads free online historical images as the base map (no plug-ins are required)
Continuous soul torture from two MySQL indexes of interviewers
Modify stm32f030 clock source to internal crystal oscillator (HEI)
Monotone stack and its application
STM32CubeIDE SWV功能使用方法
美国众议院议员:数字美元将支持美元作为全球储备货币
Stm32f030f4 reading infrared remote control data
Morris遍历
7-8 ladder cloud vertical
Window system installation Nacos
QT display RGB data