Hibernate Getting Started Tutorial

Source: Internet
Author: User

Hibernate

Arbitrary use of object-oriented ideas to manipulate the database.


Table of Contents
    • Introduced
    • Build the development environment
    • Half-SQL semi-object-oriented notation
    • A complete SQL notation
    • Complete object-oriented notation
Hibernate

Hibernate is an open-source object-relational mapping framework that provides JDBC with a very lightweight object encapsulation that maps Pojo to database tables, and hibernate can automatically generate SQL statements, automatically execute them, Allows Java programmers to use object programming thinking to manipulate databases without regard to whether database implementations are SQL Server or MySQL or Oracle

Build the Environment

Built in general engineering

    1. Jar Download
    2. Configuration file
Jar Download

After the official website hibernate to see Hibenate ORM, click More, the left sidebar select a version of releases, the bottom of the page, select download Download can
Official jar Package: Lib file: All the jar copies in the requeired file to your new project, and then add the connection database related package, Mysql-connector

Configuration file

Hibernate.cfg.xmlPlaced under SRC, need to modify url,username and password

    <?xmlversion='1.0'encoding='utf-8'?>    <!DOCTYPEhibernate-configurationPUBLIC    "-//Hibernate/HibernateConfigurationDTD//EN"    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">        

Node.hbm.xmlMap to specific Pojo, one Pojo to configure a mapped XML
Name and database name even the same, you need to write the property mapping

    <?xml version= ' 1.0 ' encoding= ' utf-8 '?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge. Net/hibernate-mapping-3.0.dtd "> 

Pojo Primary key property name corresponds to the primary key name of the database entity written in ID
, others are written in the property.

Half-SQL semi-object-oriented notation
    • Single data (objects) stored in the database
    • Querying a single object
    • Update a single object
    • Delete Object
    • Querying the entire table
    • Querying a property of an object
    • Querying the specified row data
    • query specifies that data is passed back to an entity
    • grouping aggregations
    • Sort
    • Limit
    • Using Parameters
    • Inch
    • Write in config file

In an entry method or test class method, add the

//构建上下文换肩加配置连接池,开启事务Configuration configuration = new Configuration().configure();SessionFactory sessionFactory = configuration.buildSessionFactory();Session session = sessionFactory.openSession();Transaction transaction = session.beginTransaction();//这里填写测试代码//提交事务并关闭各种流transaction.commit();session.close();sessionFactory.close();

The following test code, respectively, is placed in the above code ' 这里填写测试代码 place

Single data store to database
    Node node = new Node();;    node.setNodeId("testNodeId1");    node.setPid("testPid1");    node.setType((byte)1);    node.setLevel((short)1);    node.setName("testName1");    session.save(node);  
Querying a single object
Node node=(Node)session.get(Node.class,1);System.out.println(node);//Node.class后面的1是数据库中的主键值  
Update a single object
Node node=(Node)session.get(Node.class,10);node.setName("updateName");session.update(node);  
Delete Object
Node node = (Node) session.get(Node.class, 10);session.delete(node);  
Querying the entire table

It is important to note that if your pojo is called MyUser, and the corresponding table in the database is called user, all the places that use CreateQuery are related to the table, it should be filled myuser

Query query = session.createQuery("FROM Node");List list = query.list();System.out.println("list = " + list);  
Querying a property of an object
Query query = session.createQuery("SELECT nodeId FROM Node");List list = query.list();System.out.println("list = " + list);  
Querying the specified row data
Query query = session.createQuery("FROM Node WHERE type=?");query.setParameter(0,10);List list = query.list();System.out.println("list = " + list);  
query specifies that data is passed back to an entity
//需要pojo有相应的构造器Query query = session.createQuery("SELECT new Node(id,name,nodeId) FROM Node");List<Node> list = query.list();System.out.println("list = " + list);  
grouping aggregations
Query query = session.createQuery("SELECT type,SUM(id) FROM Node GROUP BY type");List list = query.list();for (Object o : list) {    Object[] result = (Object[]) o;    System.out.println(Arrays.toString(result));}  
Sort
Query query = session.createQuery("FROM Node ORDER BY id DESC");List list = query.list();System.out.println("list = " + list);  
Limit
Query query = session.createQuery("FROM Node ORDER BY id DESC");query.setFirstResult(2);query.setMaxResults(3);List list = query.list();System.out.println("list = " + list);  
Using Parameters
String colName = "id";String sql = "FROM Node WHERE " + colName + "=?";Query query = session.createQuery(sql);query.setParameter(0,6);Node node = (Node) query.uniqueResult();System.out.println("node = " + node);  

or this

Query query = session.createQuery("FROM Node WHERE id:id");query.setParameter("id",7);List list = query.list();System.out.println("list = " + list);  
Inch
Query query = session.createQuery("FROM Node WHERE id IN(:ids)");query.setParameterList("ids",new Object[]{4,6,7});List list = query.list();System.out.println("list = " + list);//In 的效率很低
Write in config file

User.hbm.xml

Code section

Query query = session.getNamedQuery("getUserByAge");query.setParameter(0,6);query.setParameter(1,8);List list = query.list();System.out.println("list = " + list);  
A complete SQL notation

In the first half-SQL notation, the format changes can be

1. Native SQL notation

SQLQuery query = session.createSQLQuery("SELECT * FROM tree");query.addEntity(Node.class);List list = query.list();System.out.println("list = " + list);  
Complete object-oriented notation

In the first half-SQL notation, the format changes can be

Criteria criteria = session.createCriteria(Node.class);criteria.add(Restrictions.eq("id",6));List list = criteria.list();System.out.println("list = " + list);  

It's the equivalent of finding out all of them in the criteria.

    • Not equal to
    • Sort
    • Add pagination
    • grouping aggregations
Not equal to
Criteria criteria = session.createCriteria(Node.class);criteria.add(Restrictions.ne("id",1));List list = criteria.list();System.out.println("list = " + list);  
Sort
Criteria criteria = session.createCriteria(Node.class);criteria.addOrder(Order.desc("id"));List list = criteria.list();System.out.println("list = " + list);  
Add pagination
Criteria criteria = session.createCriteria(Node.class);criteria.add(Restrictions.ne("id",1));criteria.setFirstResult(0);criteria.setMaxResults(2);List list = criteria.list();System.out.println("list = " + list);  
grouping aggregations
Criteria criteria = session.createCriteria(Node.class);ProjectionList projectionList = Projections.projectionList();projectionList.add(Projections.sum("id"));projectionList.add(Projections.groupProperty("type"));criteria.setProjection(projectionList);List list = criteria.list();for (Object o : list) {    Object[] result = (Object[]) o;System.out.println(Arrays.toString(result));}

Hibernate Getting Started Tutorial

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.