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

边栏推荐
- Why do more and more physical stores use VR panorama? What are the advantages?
- The file containing the file operation vulnerability (6)
- ∞ symbol line animation canvasjs special effect
- Hydropower project construction scheme based on 3D GIS Development
- JS listens for page or element scroll events, scrolling to the bottom or top
- Tomorrow is the PMP Exam (June 25). Have you understood all this?
- Today's sleep quality record 79 points
- Investment analysis and prospect forecast report of global and Chinese octadecyl cyclopentanoate industry from 2022 to 2028
- throttle-debounce.js:一个小型的防抖节流函数库
- Using external Libpcap library on ARM platform
猜你喜欢
随机推荐
7-8 circular scheduling problem
5年,从“点点点”到现在的测试开发,我的成功值得每一个借鉴。
The living standards of ordinary people
年薪百万,7年测试经验:守在一个还算不错的赛道,慢慢积累,等风来
Phprunner 10.7.0 PHP code generator
Daily calculation (vowel case conversion)
7-5 maximal submatrix sum problem
磁带svg动画js特效
JPA学习1 - 概述、JPA、JPA核心注解、JPA核心对象
canvas螺旋样式的动画js特效
Scala IO writes data to a text file
7-7 digital triangle
VR全景制作的优势是什么?为什么能得到青睐?
Ultra vires vulnerability & Logic vulnerability (hot) (VIII)
Analysis report on operation mode and future development of global and Chinese methyl cyclopentanoate industry from 2022 to 2028
Today's sleep quality record 79 points
有趣的checkbox计数器
Hibernate学习3 - 自定义SQL
去商场逛街
Using ADC to control brushless motor source program STM32 library function









