当前位置:网站首页>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();
}
边栏推荐
- Tiktok practice ~ upload and release app video
- Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
- Leetcode topic [array] -39- combined sum
- Fast pace? high pressure? VR panoramic Inn brings you a comfortable life
- Using external Libpcap library on ARM platform
- 教程详解|在酷雷曼系统中如何编辑设置导览功能?
- Design and practice of vivo server monitoring architecture
- Tongji and Ali won the CVPR best student thesis, lifeifei won the Huang xutao award, and nearly 6000 people attended the offline conference
- Printf redirection of serial port under sw4stm32 (SW4)
- Using ADC to control brushless motor source program STM32 library function
猜你喜欢
Spark's wide dependence and narrow dependence yyds dry goods inventory
抖音實戰~項目關聯UniCloud
Understanding openstack network
美国众议院议员:数字美元将支持美元作为全球储备货币
Ultra vires vulnerability & Logic vulnerability (hot) (VIII)
DO280OpenShift访问控制--加密和ConfigMap
Morris traversal
基于三维GIS开发的水电工程建设方案
Harmonyos accessing database instances (3) -- use ORM bee to test how good harmonyos is
go 语言指针,值引用和指针引用
随机推荐
DO280OpenShift访问控制--加密和ConfigMap
ArcGIS loads free online historical images as the base map (no plug-ins are required)
Sitelock helps you with the top ten common website security risks
机器学习自学成才的十条戒律
Volcano becomes spark default batch scheduler
Hyperledger Fabric 2. X dynamic update smart contract
Tutorial details | how to edit and set the navigation function in the coolman system?
Hello C (III) - pointer
抖音实战~发布短视频流程梳理
7-6 laying oil well pipeline
Laravel framework knowledge
(Smooth)ScrollToPosition doesn't work properly with RecyclerView
SAP PA certificate for no birds, which can be tested by new peers
Mirror image of sword finger offer binary tree
Helix distance of point
Canvas spiral style animation JS special effect
Yyds dry goods inventory tells us 16 common usage scenarios of redis at one go
STM32CubeIDE SWV功能使用方法
Scala IO reads data from URLs and other data sources
Huawei machine learning service speech recognition function enables applications to paint "sound" and color