Category.java

package com.bjsxt.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; @Entity
public class Category {
private int id;
private String name;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Topic.java

package com.bjsxt.hibernate;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne; @Entity
public class Topic {
private int id;
private String title;
private Category category;
//private Category category2; private Date createDate; public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@ManyToOne(fetch=FetchType.LAZY)
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
} }

Msg

package com.bjsxt.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne; @Entity
public class Msg {
private int id;
private String cont;
private Topic topic;
@ManyToOne
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} public String getCont() {
return cont;
}
public void setCont(String cont) {
this.cont = cont;
} }

Msginfo

package com.bjsxt.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne; public class MsgInfo { //VO DTO Value Object username p1 p2 UserInfo->User->DB
private int id;
private String cont;
private String topicName;
private String categoryName;
public MsgInfo(int id, String cont, String topicName, String categoryName) {
super();
this.id = id;
this.cont = cont;
this.topicName = topicName;
this.categoryName = categoryName;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} public String getCont() {
return cont;
}
public void setCont(String cont) {
this.cont = cont;
} }

Test

test1

    @Test
public void testHQL_01() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Category"); //ql语言
List<Category> categories = (List<Category>)q.list(); //取出对象
for(Category c : categories) {
System.out.println(c.getName());
}
session.getTransaction().commit();
session.close(); }

@Test
public void testHQL_02() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Category c where c.name > 'c5'");     //是对象而不是表名字
List<Category> categories = (List<Category>)q.list();             //返回一个对象数组
for(Category c : categories) {
System.out.println(c.getName());
}
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_03() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Category c order by c.name desc");    //逆序
List<Category> categories = (List<Category>)q.list();   //返回对象数组
for(Category c : categories) {
System.out.println(c.getName());
}
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_04() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select distinct c from Category c order by c.name desc");     //没有重复的主键
List<Category> categories = (List<Category>)q.list();
for(Category c : categories) {
System.out.println(c.getName());
}
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_05() {
Session session = sf.openSession();
session.beginTransaction();
/*Query q = session.createQuery("from Category c where c.id > :min and c.id < :max");   //:相当于占位符
//q.setParameter("min", 2);            //设置min值
//q.setParameter("max", 8);            //设置max值,也可以用下面这种设法
q.setInteger("min", 2);
q.setInteger("max", 8);*/

Query q = session.createQuery("from Category c where c.id > :min and c.id < :max")
.setInteger("min", 2)
.setInteger("max", 8);
List<Category> categories = (List<Category>)q.list();
for(Category c : categories) {
System.out.println(c.getId() + "-" + c.getName());
}
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_06() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Category c where c.id > ? and c.id < ?");    //另外一种设法
q.setParameter(0, 2)
.setParameter(1, 8);
// q.setParameter(1, 8);
List<Category> categories = (List<Category>)q.list();
for(Category c : categories) {
System.out.println(c.getId() + "-" + c.getName());
}
session.getTransaction().commit();
session.close();

}
//分页
@Test
public void testHQL_07() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Category c order by c.name desc");
q.setMaxResults(4);        //设置每页的
q.setFirstResult(2);   //设置起始
List<Category> categories = (List<Category>)q.list();
for(Category c : categories) {
System.out.println(c.getId() + "-" + c.getName());
}
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_08() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select c.id, c.name from Category c order by c.name desc");
List<Object[]> categories = (List<Object[]>)q.list();
for(Object[] o : categories) {
System.out.println(o[0] + "-" + o[1]);
}
session.getTransaction().commit();
session.close();

}

//设定fetch type 为lazy后将不会有第二条sql语句
@Test
public void testHQL_09() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.category.id = 1");
List<Topic> topics = (List<Topic>)q.list();
for(Topic t : topics) {
System.out.println(t.getTitle());
//System.out.println(t.getCategory().getName());
}
session.getTransaction().commit();
session.close();

}

//设定fetch type 为lazy后将不会有第二条sql语句
@Test
public void testHQL_10() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.category.id = 1");
List<Topic> topics = (List<Topic>)q.list();
for(Topic t : topics) {
System.out.println(t.getTitle());
}
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_11() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.topic.category.id = 1");           //导航 因为有多对一的关系

for(Object o : q.list()) {
Msg m = (Msg)o;
System.out.println(m.getCont());
}
session.getTransaction().commit();
session.close();

}
//了解即可
//VO Value Object
//DTO data transfer object
@Test
public void testHQL_12() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select new com.bjsxt.hibernate.MsgInfo(m.id, m.cont, m.topic.title, m.topic.category.name) from Msg");

for(Object o : q.list()) {
MsgInfo m = (MsgInfo)o;
System.out.println(m.getCont());
}
session.getTransaction().commit();
session.close();

}

//动手测试left right join
//为什么不能直接写Category名,而必须写t.category
//因为有可能存在多个成员变量(同一个类),需要指明用哪一个成员变量的连接条件来做连接
@Test
public void testHQL_13() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select t.title, c.name from Topic t join t.category c "); //join Category c
for(Object o : q.list()) {
Object[] m = (Object[])o;
System.out.println(m[0] + "-" + m[1]);
}
session.getTransaction().commit();
session.close();

}

//学习使用uniqueResult
@Test
public void testHQL_14() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m = :MsgToSearch "); //不重要
Msg m = new Msg();
m.setId(1);
q.setParameter("MsgToSearch", m);

Msg mResult = (Msg)q.uniqueResult();   /返回唯一的一个
System.out.println(mResult.getCont());
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_15() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select count(*) from Msg m");   //返回数量

long count = (Long)q.uniqueResult();
System.out.println(count);
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_16() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select max(m.id), min(m.id), avg(m.id), sum(m.id) from Msg m");

Object[] o = (Object[])q.uniqueResult();
System.out.println(o[0] + "-" + o[1] + "-" + o[2] + "-" + o[3]);
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_17() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.id between 3 and 5");

for(Object o : q.list()) {
Msg m = (Msg)o;
System.out.println(m.getId() + "-" + m.getCont());
}
session.getTransaction().commit();
session.close();

}

@Test
public void testHQL_18() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.id in (3,4, 5)");

for(Object o : q.list()) {
Msg m = (Msg)o;
System.out.println(m.getId() + "-" + m.getCont());
}
session.getTransaction().commit();
session.close();

}

//is null 与 is not null
@Test
public void testHQL_19() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Msg m where m.cont is not null");

for(Object o : q.list()) {
Msg m = (Msg)o;
System.out.println(m.getId() + "-" + m.getCont());
}
session.getTransaction().commit();
session.close();

}

 

pART2

更改Topic

package com.bjsxt.hibernate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List; import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany; @Entity
@NamedQueries(
{
@NamedQuery(name="topic.selectCertainTopic", query="from Topic t where t.id = :id")
}
)
/*
@NamedNativeQueries(
{
@NamedNativeQuery(name="topic.select2_5Topic", query="select * from topic limit 2, 5")
}
)
*/ public class Topic {
private int id;
private String title;
private Category category;
private Date createDate;
private List<Msg> msgs = new ArrayList<Msg>();
@OneToMany(mappedBy="topic")
public List<Msg> getMsgs() { return msgs;
}
public void setMsgs(List<Msg> msgs) {
this.msgs = msgs;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@ManyToOne(fetch=FetchType.LAZY)
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
} }
@Test
public void testHQL_20() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.msgs is empty"); for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getId() + "-" + t.getTitle());
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_21() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.title like '%5'"); for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getId() + "-" + t.getTitle());
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_22() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.title like '_5'"); for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getId() + "-" + t.getTitle());
}
session.getTransaction().commit();
session.close(); }
//不重要
@Test
public void testHQL_23() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select lower(t.title)," +
"upper(t.title)," +
"trim(t.title)," +
"concat(t.title, '***')," +
"length(t.title)" +
" from Topic t "); for(Object o : q.list()) {
Object[] arr = (Object[])o;
System.out.println(arr[] + "-" + arr[] + "-" + arr[] + "-" + arr[] + "-" + arr[] + "-");
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_24() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select abs(t.id)," +
"sqrt(t.id)," +
"mod(t.id, 2)" +
" from Topic t "); for(Object o : q.list()) {
Object[] arr = (Object[])o;
System.out.println(arr[] + "-" + arr[] + "-" + arr[] );
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_25() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select current_date, current_time, current_timestamp, t.id from Topic t"); for(Object o : q.list()) {
Object[] arr = (Object[])o;
System.out.println(arr[] + " | " + arr[] + " | " + arr[] + " | " + arr[]);
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_26() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.createDate < :date");
q.setParameter("date", new Date());
for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getTitle());
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_27() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select t.title, count(*) from Topic t group by t.title") ;
for(Object o : q.list()) {
Object[] arr = (Object[])o;
System.out.println(arr[] + "|" + arr[]);
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_28() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("select t.title, count(*) from Topic t group by t.title having count(*) >= 1") ;
for(Object o : q.list()) {
Object[] arr = (Object[])o;
System.out.println(arr[] + "|" + arr[]);
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_29() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.id < (select avg(t.id) from Topic t)") ;
for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getTitle());
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_30() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("from Topic t where t.id < ALL (select t.id from Topic t where mod(t.id, 2)= 0) ") ;
for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getTitle());
}
session.getTransaction().commit();
session.close(); } //用in 可以实现exists的功能
//但是exists执行效率高
@Test
public void testHQL_31() {
Session session = sf.openSession();
session.beginTransaction();// t.id not in (1)
Query q = session.createQuery("from Topic t where not exists (select m.id from Msg m where m.topic.id=t.id)") ;
// Query q = session.createQuery("from Topic t where exists (select m.id from Msg m where m.topic.id=t.id)") ;
for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getTitle());
}
session.getTransaction().commit();
session.close(); } //update and delete
//规范并没有说明是不是要更新persistent object,所以如果要使用,建议在单独的trasaction中执行 @Test
public void testHQL_32() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.createQuery("update Topic t set t.title = upper(t.title)") ; q.executeUpdate();
q = session.createQuery("from Topic");
for(Object o : q.list()) {
Topic t = (Topic)o;
System.out.println(t.getTitle());
}
session.createQuery("update Topic t set t.title = lower(t.title)")
.executeUpdate();
session.getTransaction().commit();
session.close(); } //不重要
@Test
public void testHQL_33() {
Session session = sf.openSession();
session.beginTransaction();
Query q = session.getNamedQuery("topic.selectCertainTopic");
q.setParameter("id", );
Topic t = (Topic)q.uniqueResult();
System.out.println(t.getTitle());
session.getTransaction().commit();
session.close(); } //Native(了解)
@Test
public void testHQL_34() {
Session session = sf.openSession();
session.beginTransaction();
SQLQuery q = session.createSQLQuery("select * from category limit 2,4").addEntity(Category.class);
List<Category> categories = (List<Category>)q.list();
for(Category c : categories) {
System.out.println(c.getName());
}
session.getTransaction().commit();
session.close(); } @Test
public void testHQL_35() {
//尚未实现JPA命名的NativeSQL }

QBC

@Test
public void testQBC() {
Session session = sf.openSession();
session.beginTransaction();
//criterion 标准/准则/约束
Criteria c = session.createCriteria(Topic.class) //from Topic .add(Restrictions.gt("id", )) //greater than = id > 2
.add(Restrictions.lt("id", )) //little than = id < 8
.add(Restrictions.like("title", "t_"))
.createCriteria("category")
.add(Restrictions.between("id", , )) //category.id >= 3 and category.id <=5
;
//DetachedCriterea
for(Object o : c.list()) {
Topic t = (Topic)o;
System.out.println(t.getId() + "-" + t.getTitle());
}
session.getTransaction().commit();
session.close(); }

QBE

@Test
public void testSave() {
Session session = sf.openSession();
session.beginTransaction(); for(int i=; i<; i++) {
Category c = new Category();
c.setName("c" + i);
session.save(c);
} for(int i=; i<; i++) {
Category c = new Category();
c.setId();
Topic t = new Topic();
t.setCategory(c);
t.setTitle("t" + i);
t.setCreateDate(new Date());
session.save(t); } for(int i=; i<; i++) { Topic t = new Topic();
t.setId();
Msg m = new Msg();
m.setCont("m" + i);
m.setTopic(t);
session.save(m); } session.getTransaction().commit();
session.close();
} //is empty and is not empty
//query by criteria query by example
@Test
public void testQBE() {
Session session = sf.openSession();
session.beginTransaction();
Topic tExample = new Topic();
tExample.setTitle("T_"); Example e = Example.create(tExample)
.ignoreCase().enableLike();
Criteria c = session.createCriteria(Topic.class)
.add(Restrictions.gt("id", ))
.add(Restrictions.lt("id", ))
.add(e)
; for(Object o : c.list()) {
Topic t = (Topic)o;
System.out.println(t.getId() + "-" + t.getTitle());
}
session.getTransaction().commit();
session.close(); }

Hibernate 再接触 HQL的更多相关文章

  1. Hibernate 再接触 基础配置 搭建Log4j环境 Junit日志环境等

    <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.aut ...

  2. Hibernate 再接触 CRUD

    1.save 一对多双向 package com.bjsxt.hibernate; import java.util.HashSet; import java.util.Set; import jav ...

  3. Hibernate 再接触 核心开发接口

    1.可以重载方法进行配置文件的指定 sessionFactory = new AnnotationConfiguration().configure("hibernate.xml" ...

  4. Hibernate 再接触 悲观锁和乐观锁

    为什么取1248 二进制 CRUD 移位效率高 在并发和效率选择一个平衡点 一般不会考虑幻读 因为我们不会再一个事务里查询两次,(只能设置为seralizable) 悲观锁和乐观锁的前提是read-u ...

  5. Hibernate 再接触 一级缓存 二级缓存 查询缓存

    缓存 就是把本来应该放在硬盘里的东西放在内存里  将来存内存里读 一级缓存: session缓存 二级缓存: sessionFactory级别的   (适合经常访问,数据量有限,改动不大) 很多的se ...

  6. Hibernate 再接触 性能优化

    Sessionclear 否则session缓存里越来越多 Java有内存泄露吗? 在语法中没有(垃圾自动回收) 但是在实际中会有 比如读文件没有关什么的 1+N问题 解决方法:把fetch设置为la ...

  7. Hibernate 再接触 ID生成策略

    Xml 方法 在student.hbm.xml中 <generator class="uuid"></generator> 取值如下 1.identity: ...

  8. Hibernate 再接触 树状结构设计以及学生课程成绩表的设计

    1 树状结构的设计 package com.bjsxt.hibernate; import java.util.HashSet; import java.util.Set; import javax. ...

  9. Hibernate 再接触 继承映射

    用一张 每一个类一张表 建立外键 第一种 一张总表 Person package com.bjsxt.hibernate; import javax.persistence.Discriminator ...

随机推荐

  1. L2-024. 部落(并查集)*

    L2-024. 部落 参考博客 #include<cstdio> #include<iostream> #include<set> #include<algo ...

  2. pycharm 设置参数,快捷键

    pycharm 设置参数 当编写代码的时候出现红色下划线提示,表示有异常,此时需要导入此模块 参数设置 设置完参数之后执行一下看看效果 这里面0为脚本本身,1为刚才设置的参数hello 快捷键设置 常 ...

  3. Ubuntu16.04上添加用户以及修改用户所属的组

    我的问题是这样的,我的本地的电脑上有一个用户以及一个用户组,我还想添加其他的用户,并且这个用户属于这个已有的用户组 <鸟哥的linux私房菜>针对的是centos系统,还是有一些不一样 实 ...

  4. 【开发遇到的问题】Spring Mvc使用Jackson进行json转对象时,遇到的字符串转日期的异常处理(JSON parse error: Can not deserialize value of type java.util.Date from String[)

    1.问题排查 - 项目配置 springboot 2.1 maven配置jackson - 出现的场景: 服务端通过springmvc写了一个对外的接口,查询数据中的表,表中有一个字段属性是时间戳,返 ...

  5. [Split The Tree][dfs序+树状数组求区间数的种数]

    Split The Tree 时间限制: 1 Sec  内存限制: 128 MB提交: 46  解决: 11[提交] [状态] [讨论版] [命题人:admin] 题目描述 You are given ...

  6. 什么是web前端开发?

    Web前端开发工程师,主要职责是利用(X)HTML/CSS/JavaScript/Flash等各种Web技术进行客户端产品的开发.完成客户端程序(也就是浏览器端)的开发,开发JavaScript以及F ...

  7. 在xcode 上调试c程序

    打开xcode 选择 Create a new Xcode project 选择Command Line Tool 给你的项目起个名,选择c语言 点击next 选择存储位置,就会制动生成一个项目,在项 ...

  8. 兼容ie,火狐的判断回车键js脚本

    var event = window.event || arguments.callee.caller.arguments[0]; var keycode = event.keyCode || eve ...

  9. ef中文文档

    https://entityframework.net/zh-CN/home 在使用ef进行对数据库操作时 数据库迁移 https://www.dotnettricks.com/learn/entit ...

  10. 02-Introspector内省设置单个属性

    package com.oa.test; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; ...