zoukankan      html  css  js  c++  java
  • hibernate注解开发,三种查询语句

    Hibernate注解开发

      首先举个例子(PO类注解配置)

    @Entity
    @Table(name="t_book")
    public class Book {
        @Id
        @GenericGenerator(name="myuuid",strategy="uuid")
        @GeneratedValue(generator="myuuid")
        private String id;
        @Column(name="b_name")
        private String name;
        @Temporal(TemporalType.TIMESTAMP)
        private Date date;
        @Transient
        private Double price;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Date getDate() {
            return date;
        }
        public void setDate(Date date) {
            this.date = date;
        }
        public Double getPrice() {
            return price;
        }
        public void setPrice(Double price) {
            this.price = price;
        }
        @Override
        public String toString() {
            return "Book [id=" + id + ", name=" + name + ", date=" + date + ", price=" + price + "]";
        }
    }

    @Entity 声明一个实体
    @Table来描述类与表对应
    @Id来声明一个主键
    @GenerateValue 用它来声明一个主键生成策略

      默认情况下相当于native,可以选择的主键生成策略 AUTO IDENTITY SEQUENCE

    @Column来定义列

    @Temporal来声明日期类型

      TemporalType.DATA   只有年月日,TemporalType.TIME   只有小时分钟秒,TemporalType.TIMESTAMP 有年月日小时分钟秒

    最后我们在hibernate.cfg.xml文件中将我们的类中的注解引用生效

    <mapping class="com.learn.domain.Book"/>

      一对多关系注解配置(描述一个客户拥有多个订单)

    一个客户类:

    @Entity
    @Table(name="t_customer")
    public class Customer {
        @Id
        @GenericGenerator(name="myuuid",strategy="uuid")
        @GeneratedValue(generator="myuuid")
        /*
         * Id代表主键声明
         * GenericGenerator声明一个主键生成策略
         * GeneratedValue引用一个主键生成策略
         * */
        private String id;
        @Column(name="c_name")
        private String name;
        @OneToMany(targetEntity=Order.class,mappedBy="c")
        @Cascade(CascadeType.SAVE_UPDATE)
        //mappedBy代表外键交给多的一方来维护
        private Set<Order> orders = new HashSet<>();
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Set<Order> getOrders() {
            return orders;
        }
        public void setOrders(Set<Order> orders) {
            this.orders = orders;
        }
        @Override
        public String toString() {
            return "Customer [id=" + id + ", name=" + name + "]";
        }
        
    }

    一个订单类:

    @Entity
    @Table(name="t_order")
    public class Order {
        @Id
        @GenericGenerator(name="myuuid",strategy="uuid")
        @GeneratedValue(generator="myuuid")
        private String id;
        @Column(name="o_name")
        private String name;
        @ManyToOne(targetEntity=Customer.class)
        @JoinColumn(name="c_customer_id")    //指定外键列
        private Customer c = new Customer();
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Customer getC() {
            return c;
        }
        public void setC(Customer c) {
            this.c = c;
        }
        @Override
        public String toString() {
            return "Order [id=" + id + ", name=" + name + ", c=" + c + "]";
        }
    }

    需要注意的是mappedBy它代表的是外键由哪一方来维护,如果是例子中的有引用c的Order类来维护,在保存订单时,就需要
    声明关系,简单来说就是要添加订单与客户关系的代码

    对于cascade注解,这里在customer中配置了@Cascade(CascadeType.SAVE_UPDATE),这就表示保存客户自动保存订单

      多对多关系(一个老师可以有多个学生,一个学生也可以有多个老师)

    学生类:

    @Entity
    @Table(name="t_student")
    public class Student {
        @Id
        @GenericGenerator(name="myuuid",strategy="uuid")
        @GeneratedValue(generator="myuuid")
        private String id;
        @Column(name="s_name")
        private String name;
        @ManyToMany(targetEntity=Teacher.class,mappedBy="students")
        private Set<Teacher> teachers = new HashSet<>();
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Set<Teacher> getTeachers() {
            return teachers;
        }
        public void setTeachers(Set<Teacher> teachers) {
            this.teachers = teachers;
        }
        @Override
        public String toString() {
            return "Student [id=" + id + ", name=" + name + "]";
        }
    }

    老师类:

    @Entity
    @Table(name="t_teacher")
    public class Teacher {
        @Id
        @GenericGenerator(name="myuuid",strategy="uuid")
        @GeneratedValue(generator="myuuid")
        private String id;
        @Column(name="t_name")
        private String name;
        @ManyToMany(targetEntity=Student.class)
        @JoinTable(name="s_t",joinColumns={@JoinColumn(name="t_teacher_id")},inverseJoinColumns={@JoinColumn(name="s_student_id")})
        @Cascade(CascadeType.SAVE_UPDATE)
        /**
         * ManyToMany代表关联对象的class(简单点说就是set中的泛型)
         * JoinTable描述中间表
         * joinColumns就是描述本类中的表与中间表的关系
         * inverseJoinColumns用来描述另一个表与中间表的关系
         * */
        private Set<Student> students = new HashSet<>();
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Set<Student> getStudents() {
            return students;
        }
        public void setStudents(Set<Student> students) {
            this.students = students;
        }
        @Override
        public String toString() {
            return "Teacher [id=" + id + ", name=" + name + ", students=" + students + "]";
        }
    }

      一对一关系(用户和身份编号)

    用户类:

    @Entity
    @Table(name="t_user")
    public class User {
        @Id
        @GenericGenerator(name="myuuid",strategy="uuid")
        @GeneratedValue(generator="myuuid")
        private String id;
        @Column(name="u_name")
        private String name;
        @OneToOne(targetEntity=IDCard.class,mappedBy="user")
        private IDCard idCard;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public IDCard getIdCard() {
            return idCard;
        }
        public void setIdCard(IDCard idCard) {
            this.idCard = idCard;
        }
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + "]";
        }
    }

    身份类:

    @Entity
    @Table(name="t_idcard")
    public class IDCard {
        @Id
        @GenericGenerator(name="myuuid",strategy="uuid")
        @GeneratedValue(generator="myuuid")
        private String id;
        @Column(name="i_cardnum")
        private String cardNum;
        @OneToOne(targetEntity=User.class)
        @JoinColumn(name="c_user_id")    //joinColumn指定外键列名称
        @Cascade(CascadeType.SAVE_UPDATE)
        private User user;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getCardNum() {
            return cardNum;
        }
        public void setCardNum(String cardNum) {
            this.cardNum = cardNum;
        }
        public User getUser() {
            return user;
        }
        public void setUser(User user) {
            this.user = user;
        }
        @Override
        public String toString() {
            return "IDCard [id=" + id + ", cardNum=" + cardNum + ", user=" + user + "]";
        }
    }

    HQL

    public class TestHQL {
        //准备数据
        @Test
        public void test1() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Customer c = new Customer();
            c.setName("猥琐逼");
            
            for (int i = 0; i < 10; i++) {
                Order order = new Order();
                order.setMoney(2000+i*10d);
                order.setReceiverInfo("日本");
                order.setC(c);
                session.save(order);
            }
            
            
            session.getTransaction().commit();
            session.close();
        }
        //基本索引
        @Test
        public void test2() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Query query = session.createQuery("from Customer");
            List<Customer> list = query.list();
            System.out.println(list);
            session.getTransaction().commit();
            session.close();
        }
        
        //排序索引
        @Test
        public void test3() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Query query = session.createQuery("from Order order by money desc");
            List<Order> list = query.list();
            System.out.println(list);
            
            
            session.getTransaction().commit();
            session.close();
        }
        
        //条件检索
        @Test
        public void test4() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Query query = session.createQuery("from Order where money > ?");
            query.setParameter(0, 2000d);
            
            List<Order> list = query.list();
            System.out.println(list);
            
            
            session.getTransaction().commit();
            session.close();
        }
        //分页检索
        @Test
        public void test5() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Query query = session.createQuery("from Order");
            query.setFirstResult(11);
            query.setMaxResults(6);
            
            List<Order> list = query.list();
            System.out.println(list);
            
            session.getTransaction().commit();
            session.close();
        }
        //分页统计检索
        @Test
        public void test6() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            /*Query query = session.createQuery("select count(*) from Order");
            
            Object count = query.uniqueResult();
            System.out.println(count);*/
            
            Query query = session.createQuery("select sum(money) from Order group by c");
            //需要注意的是group by c,其中的c是引用的Customer对象
            List list = query.list();
            
            System.out.println(list);
            session.getTransaction().commit();
            session.close();
        }
        //投影检索
        //@Test
        public void test7() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Query query = session.createQuery("select new Customer(id,name) from Customer");
            List<Customer> list = query.list();
            System.out.println(list);
            
            session.getTransaction().commit();
            session.close();
        }
    }

    QBC

    public class TestQBC {
        //基本检索
        @Test
        public void test1() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Criteria criteria = session.createCriteria(Customer.class);
            List<Customer> list = criteria.list();
            System.out.println(list);
            
            session.getTransaction().commit();
            session.close();
        }
        //排序查询
        @Test
        public void test2() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Criteria criteria = session.createCriteria(Order.class);
            criteria.addOrder(org.hibernate.criterion.Order.asc("money"));
            List list = criteria.list();
            System.out.println(list);
            
            session.getTransaction().commit();
            session.close();
        }
        //条件检索
        @Test
        public void test3() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Criteria criteria = session.createCriteria(Customer.class);
            criteria.add(Restrictions.eq("name", "猥琐逼"));
            Object result = criteria.uniqueResult();
            System.out.println(result);
            
            session.getTransaction().commit();
            session.close();
        }
        //分页查询
        @Test
        public void test4() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Criteria criteria = session.createCriteria(Order.class);
            criteria.setFirstResult(0);
            criteria.setMaxResults(2);
            List<Order> list = criteria.list();
            System.out.println(list);
            
            session.getTransaction().commit();
            session.close();
        }
        //统计分页查询
        @Test
        public void test5() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            Criteria criteria = session.createCriteria(Order.class);
            /*criteria.setProjection(Projections.rowCount());
            Object count = criteria.uniqueResult();
            System.out.println(count);*/
            
            criteria.setProjection(Projections.projectionList().add(Projections.sum("money")).add(Projections.groupProperty("c")));
            
            List<Object[]> list = criteria.list();
            for (Object[] objects : list) {
                for (Object object : objects) {
                    System.out.println(object);
                }
            }
            session.getTransaction().commit();
            session.close();
        }
        //离线条件查询
        @Test
        public void test6() {
            //创建离线查询对象
            DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
            dc.add(Restrictions.eq("name", "猥琐逼"));
            
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            //生成criteria
            Criteria criteria = dc.getExecutableCriteria(session);
            
            Customer c = (Customer) criteria.uniqueResult();
            System.out.println(c);
            
            
            session.getTransaction().commit();
            session.close();
        }
    }

    SQL

    public class TestSQL {
        //测试执行sql
        @Test
        public void test1() {
            Session session = HibernateUtils.openSession();
            session.beginTransaction();
            
            SQLQuery query = session.createSQLQuery("select * from t_customer");
            //将查询结果绑定到指定对象
            query.addEntity(Customer.class);
            List list = query.list();
            
            System.out.println(list);
            
            
            session.getTransaction().commit();
            session.close();
        }
    }
  • 相关阅读:
    封装异常处理之坑
    30multipart/form-data和application/x-www-form-urlencoded的区别(二)urlencoded之自动deocde
    使用MAT时的Shallow Size和 Retained Size的区别
    当动态代理遇到ioc
    线程池的原理
    synchroned原理与对象头(yet)
    mysql压力测试与qps监控
    一种mysql jvm死锁
    Android Jni变量对照表
    结构体中使用函数指针
  • 原文地址:https://www.cnblogs.com/learnjfm/p/7118093.html
Copyright © 2011-2022 走看看