Exemple #1
0
 /**
  * 1. 可以看到, 即使是使用这种连接方式去获取对象, 但是也会受到查出来这个对象相关的配置影响, 当查出来某个Person
  * 对象, 是否查询出IdCard那么取决于当前person.hbm.xml的对于IdCard是否立即加载。 2.
  * 所以从这里也可以看到, 当查询出某个对象的时候, 会检查当前对象的配置信息是否时查询出关联对象。所以hibernate
  * 的强大之处在于将查询出来的值打包成对象, 再通过通过对象的关联语义去查找相关联对象。
  */
 public void join() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     /**
      * 1. 此时返回的结果是非常值得去操作的, 因为返回的是类似与关联表的形式的结果, 所以一个没一行就是一个 person和一个email 2.
      * 为什么查询的第一条语句已经能够确定一个person的emails, 为什么还要去查询关联表用来确定person的emails呢? 3.
      * 可以看到这种关联查询还是非常强大的, 并不需要我们去指定关联关系, 因为hibernate以及知道这一点了。 4.
      * 每一行虽然存都存在一个person但是它却是同一个对象, 通过打印可以看到这个事实。
      */
     List<Object[]> objss =
         session
             .createQuery(
                 "from Person as p left join p.emails e where e.email like '%feng%' and p.name like '%feng%'")
             .list();
     for (Object[] objs : objss) { // 返回的行数
       System.out.println("-----------------------");
       for (Object obj : objs) { // 每一行对应的结果
         System.out.println(obj); // 没一行中的某一个结果
         //					if(obj instanceof Person){
         //						Person person = (Person) obj;
         //					}
       }
     }
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #2
0
 /**
  * 1. 可以看到select中可以直接使用一个对象表示当前所有的字段, 并且当查询出来之后直接赋值, 这样时非常强大的。 2.
  * 可以比较不同的select后面的值, 最终打包成的结果, 可以看到hibernate会为我们打包任何值对象, 并且这一切 都是自动的, 无须做任何操作
  */
 public void select() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     // 查询出那些存在邮箱的人
     List<Person> persons =
         session.createQuery("select p from Person as p inner join p.emails").list();
     for (Person person : persons) {
       System.out.println(person.getName());
     }
     // 查询出所有的人名, 可以看到这里distinct也可以使用
     List<String> names =
         session.createQuery("select distinct p.name from Person p inner join p.emails").list();
     for (String name : names) {
       System.out.println(name);
     }
     tx.rollback();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #3
0
 public void orderBy() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     session.createQuery("from Person p order by p.name").list();
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #4
0
 /**
  * 1. 使用多态查询, 但是查询的对象如果不是在hibernate的管理的实体中, 那么必须使用全限定名字。 2.
  * 所以从这里也可以看到hibernate自动导入只能导入那些以及关联了的实体对象。
  */
 public void polymorphic() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     session.createQuery("from java.lang.Object").list();
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #5
0
 public void groupBy() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     // 可以看到分组函数使用的时候必须是使用某个对象的。
     session
         .createQuery(
             "select p, count(e) from Person p left join p.emails e group by p.id order by p.name")
         .list();
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #6
0
 public void subSelect() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     session.createQuery("from Person").setFirstResult(1).setMaxResults(2).list().size();
     session
         .createSQLQuery(
             "select * from Person inner join (select id from Person limit 10, 10) a using(id)")
         .list();
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #7
0
 /**
  * 1. 简单的查询, 'from ClassName'默认情况时缺省相关的查询语句的, 并且除了类名字和属性名字其余大小写不铭感,
  * 但是小写会显得更加好。默认情况下也不需要导入类的全限定名字, 因为会自动导入。 2. 对于list而言, 关联对象会使用缓存查询, 但是iterate对于主对象而言使用的使用缓存查询
  */
 public void from() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     List<Person> persons =
         session.createQuery("from Person as p where p.name like '%linchunfeng%'").list();
     //			Iterator<Email> iterator = session.createQuery("from Email").iterate();
     //			for(;iterator.hasNext();){
     //				System.out.println(iterator.next().getEmail());
     //			}
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #8
0
 public void savePerson() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Person person = new Person();
     person.setName("linchunfeng");
     person.setAge(26);
     person.setBirthDay(new Date(1988, 11, 25));
     IdCard idCard = new IdCard();
     idCard.setNum("linchunfeng8387");
     person.setIdCard(idCard);
     Email email1 = new Email();
     email1.setEmail("*****@*****.**");
     Email email2 = new Email();
     email2.setEmail("*****@*****.**");
     Email email3 = new Email();
     email3.setEmail("*****@*****.**");
     Email email4 = new Email();
     email4.setEmail("*****@*****.**");
     Email email5 = new Email();
     email5.setEmail("*****@*****.**");
     Email email6 = new Email();
     email6.setEmail("*****@*****.**");
     Email email7 = new Email();
     email7.setEmail("*****@*****.**");
     Email email8 = new Email();
     email8.setEmail("*****@*****.**");
     person.setEmails(
         new HashSet<Email>(
             Arrays.asList(email1, email2, email3, email4, email5, email6, email7, email8)));
     session.save(person);
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #9
0
 /**
  * 1. 可以看到任何的结果是可以进行组合, 并且hibernate也完全可以进行包装, 而这一切都是免费的。 avg(...), sum(...), min(...), max(...)  *
  * count(*) count(...), count(distinct ...), count(all...)
  */
 public void gatherMethod() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     List<Object[]> lists =
         session
             .createQuery("select p, count(e) from Person p left join p.emails e group by p")
             .list();
     for (Object[] objs : lists) {
       for (Object obj : objs) {
         System.out.println(obj);
       }
     }
     tx.rollback();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #10
0
 /**
  * 1. 在 where 子句中允许使用的表达式包括 大多数你可以在 SQL 使用的表达式种类 •数学运算符 +,-,*,/ •二进制比较运算符 =, >=, <=, <>, !=, like
  * •逻辑运算符 and,or,not •括号 ( ),表示分组 •in, not in, between, is null, is not null, is empty, is not
  * empty, member of and not member of •"Simple" case, case ... when ... then ... else ... end, and
  * "searched" case, case when ... then ... else ... end •字符串连接符 ...||... or concat(...,...)
  * •current_date(), current_time(), and current_timestamp()
  * •second(...)、minute(...)、hour(...)、day(...)、month(...) 和 year(...) •EJB-QL 3.0
  * 定义的任何功能或操作符:substring(), trim(), lower(), upper(), length(), locate(), abs(), sqrt(),
  * bit_length(), mod() •coalesce() 和 nullif() •str() 把数字或者时间值转换为可读的字符串 •cast(... as ...),其第二个参数是某
  * Hibernate 类型的名字,以及 extract(... from ...),只 要 ANSI cast() 和 extract() 被底层数据库支持 •HQL index()
  * 函数,作用于 join 的有序集合的别名。 •HQL 函数,把集合作为参数:size(), minelement(), maxelement(), minindex(),
  * maxindex(),还 有特别的 elements() 和 indices 函数,可以与数量词加以限定:some, all, exists, any, in。 •任何数据库支持的 SQL
  * 标量函数,比如 sign(), trunc(), rtrim(), sin() •JDBC 风格的参数传入 ? •命名参数 :name,:start_date,:x1 •SQL 直接常量
  * 'foo', 69, 6.66E+2, '1970-01-01 10:00:01.0' •Java public static final 类型的常量 eg.Color.TABBY
  */
 public void express() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     //			session.createQuery("select p.id + p.age from Person p").list();//+ - * /
     //			Iterator<Person> iterator = session.createQuery("from Person p where
     // p.age>:age").setInteger("age", 20).iterate();
     //			System.out.println(iterator.next().getName());
     // 可以看到此处并不是查找整个的person对象, 所以iterate方法也就直接查找名字了, 这和list是完全一样的。
     // =, >=, <=, >, <, <>, !=, like, not like
     //			session.createQuery("select p.name from Person p where p.age<>:age and p.name like
     // :name").setInteger("age", 20).setString("name", "%feng%").iterate();
     // and or not
     //			session.createQuery("select p.name from Person p where p.age<>:age and p.name not like
     // :name").setInteger("age", 20).setString("name", "%feng%").iterate();
     // in, not in, between and, is null, is not null, is empty, is not empty, member of, not
     // member of
     // 这里需要说明一下, 对于is empty一般都是来判断集合的, 也就是关联对象
     //			session.createQuery("from Person p where p.emails is empty").list().size();
     // 字符串连接符 ...||... or concat(...,...)
     //			session.createQuery("select p.name || p. age from Person p").list();
     // current_date(), current_time(), and current_timestamp()
     //			session.createQuery("select current_date(), p from Person p").list();
     // second(...)、minute(...)、hour(...)、day(...)、month(...) 和 year(...)
     //			session.createQuery("select day(p.birthDay) from Person p").list();
     // substring(), trim(), lower(), upper(), length(),locate(), abs(), sqrt(), bit_length(),
     // mod()
     session.createQuery("select length(p.name), abs(p.age), str(p.age) from Person p").list();
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }
Exemple #11
0
 public void where() {
   Session session = HibernateUtils.getSessionFactory().getCurrentSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     // = != > < <> like
     List<Person> persons =
         session.createQuery("from Person where name=:name").setString("name", "feng").list();
     Person person =
         (Person)
             session
                 .createQuery("from Person p where p.name=:name")
                 .setString("name", "feng")
                 .uniqueResult();
     //			Person person2 = (Person) session.createQuery("from
     // Person").uniqueResult();//可以看到如果不是单值会报错的
     tx.commit();
   } catch (Exception e) {
     if (tx != null) {
       tx.rollback();
     }
     throw new RuntimeException(e);
   }
 }