当前位置:网站首页>Hibernate学习3 - 自定义SQL
Hibernate学习3 - 自定义SQL
2022-06-24 19:46:00 【嗯嗯**】
HQL - Hibernate Query Language
Hibernate内置的SQL查询语句 = Java代码层级的 – 只能完成SQL的删改查,不能新增
查询
普通
from关键字后面不能跟表名,必须是对应的实体类名或者类全限定名,如果项目中有类名相同的,建议直接写类全限定名,防止hibernate识别失误
添加全局where配置,只有HQL语句时才生效
<?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:类似mybatis的Bean别名type-aliases-package这个属性,用于有些属性不用写全限定名-->
<!-- default-lazy:默认启动懒加载,即一对多,多对多,多对一关系上使用-->
<!-- auto-import:默认true,是否可以在查询语句中使用非全限定名,如果项目中有两个同名的Bean,最好在两个映射文件中设置为false-->
<hibernate-mapping package="top.linruchang.entity" default-lazy="true" auto-import="false" >
<!-- dynamic-insert dynamic-update:默认都为false。true时类似 mybatisplus的代码插入Java语句,只要属性是空则update、insert的SQL语句就不会出现该列 -->
<!-- 这是定义了全局自定义SQL时会携带上where属性的条件,session.createQuery这些生效,像session.get不会生效-->
<class name="Article" table="article" dynamic-insert="true" dynamic-update="true" where="title = 'fdsfds'">
<id name="id" type="java.lang.String">
<column name="id" ></column>
<!--插入时,如果你没有设置ID,会帮你自动添加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>
@Test
public void test7() {
Configuration configure = new Configuration().configure();
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Query<Article> query = session.createQuery("from top.linruchang.entity.Article", Article.class);
List resultList = query.list();
resultList.stream().forEach(System.out::println);
transaction.commit();
session.close();
}

分页
方式1 == SQL分页
将前面映射文件的where配置去掉
@Test
public void test10() {
Configuration configure = new Configuration().configure();
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Query<SysUser> query = session.createQuery("from SysUser", SysUser.class);
query.setFirstResult(2);
query.setMaxResults(3);
query.list().stream()
.forEach(System.out::println);
transaction.commit();
session.close();
}

where
@Test
public void test10() {
Configuration configure = new Configuration().configure();
SessionFactory sessionFactory = configure.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
//特别注意 where后面的属性,必须你在该SysUserBean的映射文件中有配置,否则会出错
Query<SysUser> query = session.createQuery("from SysUser where password = 'user'", SysUser.class);
query.setFirstResult(2);
query.setMaxResults(3);
query.list().stream()
.forEach(System.out::println);
transaction.commit();
session.close();
}

占位符
@Test
public void test7() throws InterruptedException {
Configuration configure = new Configuration().configure();
//获取sessionFactory
SessionFactory sessionFactory = configure.buildSessionFactory();
//获取数据库连接session
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Query<Article> query = session.createQuery("from Article where title = :title", Article.class);
query.setParameter("title", "技术面试");
query.list().stream()
.forEach(System.out::println);
transaction.commit();
session.close();
}

级联查询
@Test
public void test8() throws InterruptedException {
Configuration configure = new Configuration().configure();
//获取sessionFactory
SessionFactory sessionFactory = configure.buildSessionFactory();
//获取数据库连接session
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
SysUser sysUser = session.get(SysUser.class, "6d72c93aa292cf2ca2e789919a5e7bdc");
System.out.println(sysUser);
//注意 sysUser必须有在映射文件中有配置,否则直接报找不到映射参数异常
Query<Article> query = session.createQuery("from Article where sysUser = :sysUser1", Article.class);
query.setParameter("sysUser1", sysUser);
query.list().stream()
.forEach(System.out::println);
transaction.commit();
session.close();
}

边栏推荐
- Hello C (I) -- basics of C language
- 普通人的生活准则
- Hyperledger Fabric 2. X dynamic update smart contract
- R语言使用epiDisplay包的aggregate函数将数值变量基于因子变量拆分为不同的子集,计算每个子集的汇总统计信息、自定义FUN参数为多个统计量函数名称的列表计算多个统计量
- throttle-debounce. JS: a small anti shake throttling function library
- From client to server
- Spark's wide dependence and narrow dependence yyds dry goods inventory
- Volcano becomes spark default batch scheduler
- R语言使用MatchIt包进行倾向性匹配分析、使用match.data函数构建匹配后的样本集合、对匹配后的样本的不同分组对应的目标变量的均值进行Welch双样本t检验分析、双独立样本t检验
- 7-6 laying oil well pipeline
猜你喜欢

企业数据防泄露解决方案分享

Today's sleep quality record 79 points

Quickly build KVM virtual machine on # yyds dry goods inventory # physical machine

Helix distance of point

抖音实战~实现App端视频上传与发布

Hydropower project construction scheme based on 3D GIS Development

点的螺旋距离

Yyds dry goods inventory tells us 16 common usage scenarios of redis at one go

Chapter VI skills related to e-learning 5 (super parameter verification)

Continuous soul torture from two MySQL indexes of interviewers
随机推荐
Solution of IP network broadcasting system in Middle School Campus - Design Guide for Campus Digital IP broadcasting system
中学校园IP网络广播系统解决方案-校园数字IP广播系统方案设计指南
Hello C (I) -- basics of C language
Hydropower project construction scheme based on 3D GIS Development
Andersen global strengthens the Middle East platform with Palestinian member companies
抖音实战~项目关联UniCloud
Tiktok practice ~ upload and release app video
376. Tâches mécaniques
How to resolve the 35 year old crisis? Sharing of 20 years' technical experience of chief architect of Huawei cloud database
Number of bytes corresponding to common data types
Basic data type
R language uses the multinom function of NNET package to build an unordered multi classification logistic regression model, and uses the AIC function to compare the AIC values of the two models (simpl
257. detention of offenders
JS listens for page or element scroll events, scrolling to the bottom or top
点的螺旋距离
7-9 treasure hunt route
Why is it that the "Zhongtai" that was originally eaten by civil engineering is no longer fragrant?
7-7 solving mode problems
Annual salary of millions, 7 years of testing experience: stay at a fairly good track, accumulate slowly, wait for the wind to come
R language uses the aggregate function of epidisplay package to split numerical variables into different subsets based on factor variables, calculate the summary statistics of each subset, and customi