当前位置:网站首页>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();
}

边栏推荐
- Printf redirection of serial port under sw4stm32 (SW4)
- 7-2 solving the stock buying problem
- canvas线条的动态效果
- 7-9 treasure hunt route
- Today's sleep quality record 79 points
- Go shopping
- Continuous soul torture from two MySQL indexes of interviewers
- Sitelock helps you with the top ten common website security risks
- Enterprise data leakage prevention solution sharing
- 7-2 construction of binary tree by post order + middle order sequence
猜你喜欢

VR全景制作的优势是什么?为什么能得到青睐?

Tape SVG animation JS effect

都2022年了,你还不了解什么是性能测试?

2021-2022 China's financial digitalization "new" insight Industry Research Report

明天就是PMP考试了(6月25日),这些大家都了解了吗?
Record a Webflux application memory leak troubleshooting

今天睡眠质量记录79分

Using ADC to control brushless motor source program STM32 library function

节奏快?压力大?VR全景客栈带你体验安逸生活

Design and practice of vivo server monitoring architecture
随机推荐
openGauss内核:简单查询的执行
创意SVG环形时钟js特效
磁带svg动画js特效
Hibernate学习3 - 自定义SQL
7-7 digital triangle
MySQL semi sync replication
2021-2022中国金融数字化“新”洞察行业研究报告
One way 和two way ANOVA分析的区别是啥,以及如何使用SPSS或者prism进行统计分析
Morris traversal
svg+js键盘控制路径
Hello C (III) - pointer
Solution of IP network broadcasting system in Middle School Campus - Design Guide for Campus Digital IP broadcasting system
使用网络摄像头进行眼睛注视估计
Analysis report on production and marketing demand and investment forecast of China's boron nitride industry from 2022 to 2028
Unveiling the secrets of the Winter Olympics | smartbi's partners supported the "front and back" of the Beijing Winter Olympics
How to use stm32subeide SWV function
美国众议院议员:数字美元将支持美元作为全球储备货币
中学校园IP网络广播系统解决方案-校园数字IP广播系统方案设计指南
JPA学习2 - 核心注解、注解进行增删改查、List查询结果返回类型、一对多、多对一、多对多
Development status and prospect trend forecast report of humic acid sodium industry in the world and China from 2022 to 2028