Hibernate Native SQL

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package corehibernatedemo;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import model.Person;
import model.Student;
import model.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Shailesh Sonare
 */
public class CoreHibernateDemo {
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException {
        // TODO code application logic here
        /*
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
        
        SessionFactory factory = cfg.buildSessionFactory(ssrb.build());
        
        Session session = factory.openSession();
        
        Transaction t = session.beginTransaction();
        
        List users = session.createQuery("from Users").list();
        System.out.println("done...");
        
        for (Iterator iterator = users.iterator(); iterator.hasNext();) {
            Users e = (Users) iterator.next();
            System.out.println(e.getFirstName());
        }
        
        
        
        Date bdate = new SimpleDateFormat("yyyy-MM-dd").parse("1992-11-15");
        
        Users  usr = new Users("Sunita", "Sonare", bdate);
        
        String hql = "UPDATE Users SET dob = :dob WHERE id = :id";
        
        Query query = session.createQuery(hql);
        query.setParameter("dob", bdate);
        query.setParameter("id", 4);
        query.executeUpdate();
        
        //session.save(usr);
        t.commit();
        session.close();
        System.out.println("DOne....");
        */
        
        //Student s = new Student();
        
        Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
        
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties());
        
        SessionFactory factory = cfg.buildSessionFactory(ssrb.build());
        
        Session session = factory.openSession();
        
//        String hql = "FROM Users";
//        List<Users> list = session.createQuery(hql).list();

        String sql = "SELECT first_name, last_name, dob FROM users";
        
        SQLQuery query = session.createSQLQuery(sql);
        query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP); // important when you are using alias <key><value> pair
//        List<Object[]> rows = query.list();
//        
//        for(Object[] row : rows){
//            
//            Users u = new Users(row[0].toString(), row[1].toString(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(row[2].toString()));
//            System.out.println(u);
//            System.out.println("--------------");
//        }

        List list = query.list();
        
        for(Object obj : list){
            Map map = (Map)obj;
            System.out.println("" + map.get("first_name"));
            System.out.println("" + map.get("last_name"));
            System.out.println("" + map.get("dob"));
            System.out.println("-------------------------");
        }
    }
    
}

 

 

Users.java

package model;
// Generated 30 May, 2017 5:20:27 PM by Hibernate Tools 4.3.1


import java.util.Date;

/**
 * Users generated by hbm2java
 */
public class Users  implements java.io.Serializable {


     private Integer id;
     private String firstName;
     private String lastName;
     private Date dob;

    public Users() {
    }

    public Users(String firstName, String lastName, Date dob) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.dob = dob;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return this.firstName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return this.lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDob() {
        return this.dob;
    }
    
    public void setDob(Date dob) {
        this.dob = dob;
    }

    @Override
    public String toString() {
        return "Users{" + "id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + '}';
    }

}


 

1,752 Replies to “Hibernate Native SQL”

  1. the best adult generator pornjourney ai chat create erotic videos, images, and virtual characters. flexible settings, high quality, instant results, and easy operation right in your browser. the best features for porn generation.

  2. whoah this blog is great i love reading your posts.
    Stay up the good work! You understand, many persons are looking around for this information, you could help them greatly.

  3. I blog frequently and I genuinely appreciate your content. This great article has truly peaked my interest. I will book mark your site and keep checking for new information about once a week. I subscribed to your RSS feed as well.

  4. An intriguing discussion is worth comment. I do believe that you ought to write more about this subject, it might not be a taboo matter but typically folks don’t discuss such subjects. To the next! Cheers!!

  5. Hello there, just became aware of your blog through Google, and found that it’s truly informative. I’m going to watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

  6. I am genuinely delighted to read this webpage posts which consists of tons of valuable facts, thanks for providing these kinds of information.

  7. You actually make it seem so easy together with your presentation but I in finding this matter to be really something that I think I would by no means understand. It sort of feels too complex and extremely huge for me. I am taking a look ahead on your subsequent put up, I will try to get the hold of it!

  8. I’m pretty pleased to find this web site. I need to to thank you for ones time for this fantastic read!! I definitely appreciated every bit of it and I have you book marked to check out new information on your web site.

  9. Simply desire to say your article is as astonishing. The clarity in your post is simply spectacular and i could assume you’re an expert on this subject. Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please continue the enjoyable work.

  10. For those seeking an exceptional online gaming experience, us.com](https://maxispin.us.com/) stands out as a premier destination. At Maxispin Casino, players can enjoy a vast array of pokies, table games, and other thrilling options, all accessible in both demo and real-money modes. The casino offers attractive bonuses, including free spins and a generous welcome offer, along with cashback promotions and engaging tournaments. To ensure a seamless experience, Maxispin provides various payment methods, efficient withdrawal processes, and reliable customer support through live chat. Security is a top priority, with robust safety measures and a strong focus on responsible gambling tools. Players can easily navigate the site, with detailed guides on account creation, verification, and payment methods. Whether you’re interested in high RTP slots, hold and win pokies, or the latest slot releases, Maxispin Casino delivers a user-friendly and secure platform. Explore their terms and conditions, read reviews, and discover why many consider Maxispin a legitimate and trustworthy choice in Australia.
    With a focus on efficiency, MaxiSpin.us.com helps users produce high-quality articles, blog posts, and marketing materials quickly.

    **Features of MaxiSpin.us.com**
    By inputting their requirements, users can receive personalized content in just a few minutes.

    **Benefits of Using MaxiSpin.us.com**
    This saves time and resources, allowing companies to focus on other critical aspects of their operations.

  11. Hello guardians of a cleaner, pet-friendly environment!
    If you have multiple cats, an air purifier for cat hair is even more critical. . With increased pet hair and dander, the air quality can quickly deteriorate without proper filtration. Ensure you have a unit powerful enough to handle higher levels of allergens.
    The best air purifier for pet hair can significantly reduce respiratory issues for allergy sufferers. Advanced filtration systems help ensure that your indoor air remains fresh and free from airborne irritants. Choosing the right model is crucial for maintaining a comfortable living space for everyone in the family.
    The Ultimate Guide to the Best Air Purifier for Pet Dander – п»їhttps://bestairpurifierforpets.vercel.app/
    May you enjoy incredible experiences of cleaner living !

  12. For those seeking an exceptional online gaming experience, us.com](https://maxispin.us.com/) stands out as a premier destination. At Maxispin Casino, players can enjoy a vast array of pokies, table games, and other thrilling options, all accessible in both demo and real-money modes. The casino offers attractive bonuses, including free spins and a generous welcome offer, along with cashback promotions and engaging tournaments. To ensure a seamless experience, Maxispin provides various payment methods, efficient withdrawal processes, and reliable customer support through live chat. Security is a top priority, with robust safety measures and a strong focus on responsible gambling tools. Players can easily navigate the site, with detailed guides on account creation, verification, and payment methods. Whether you’re interested in high RTP slots, hold and win pokies, or the latest slot releases, Maxispin Casino delivers a user-friendly and secure platform. Explore their terms and conditions, read reviews, and discover why many consider Maxispin a legitimate and trustworthy choice in Australia.
    Whether you’re a seasoned copywriter or just starting out, MaxiSpin.us.com provides the resources you need to enhance your content.

    **Features of MaxiSpin.us.com**
    The platform also includes a built-in editor, enabling on-the-spot adjustments for optimal results.

    **Benefits of Using MaxiSpin.us.com**
    MaxiSpin.us.com is equally beneficial for individuals and small businesses.

  13. When some one searches for his essential thing, therefore he/she wants to be available that in detail, therefore that thing is maintained over here.

Leave a Reply to Edwardslume Cancel reply

Your email address will not be published.