hibernte (a) introducing the

Hibernate (a)

     What is Hibernate?

       Hibernate object-relational mapping framework is an open source, it had a very lightweight JDBC object package, it will POJO mapping relationship with a database table, is a fully automated orm framework , hibernate can automatically generate SQL statements, automatically, so that the Java programmer can use arbitrary object programming thinking to manipulate the database.

We understand from three perspectives about Hibernate:

       A, Hibernate further encapsulation of JDBC

   When not using the original Hiberante do persistence layer development, there is a lot of redundancy, such as: various JDBC statement, connection management, hence the Hibernate JDBC encapsulates the moment, we do not have operational data, it will directly operate the line.

       Second, we again from the hierarchical point of view

   We know very typical three-tier architecture: presentation layer, business layer, as well as the persistence layer. Hiberante also the persistence layer framework, but there are a lot of persistence layer framework, such as: IBatis, Nhibernate, JDO, OJB, EJB, and so on.

       Three, Hibernate is an open source ORM (object-relational mapping) framework.

    ORM, ie Object-Relational Mapping, its role is in between relational databases and object made a map. Mapping from the object (Object) the relationship (Relation), and then mapped to the object from the relationship. In this way, when we operate the database, you do not need to go and deal with complex SQL, as long as the operation of the object as it can operate up (the field is mapped to a relational database attributes of an object in memory). .

     The ORM ( Object Relational the Mapping ) Frame metadata between a relational database and a map made objects. Metadata generally use XML format, and stored in a dedicated object mapping file.

       The ORM ( Object Relational the Mapping ) frame : the Hibernate (the Nhibernate) , the iBATIS , MyBatis , the EclipseLink , JFinal . Hibernate is a typical use xml file mapping framework described as physical objects ,

       Metadata : data describing other data ( Data About OTHER Data ), or data structure (for information about a resource of Structured Data ).

Language Features

       Operation of the converter will operate on the database for Java objects to simplify development. By modifying a "persistent" attribute of an object to modify data records in the database table corresponding.

       Threads and processes to provide two levels of caching to enhance application performance.

       There are a wealth of ways to convert the mapping relationships between Java objects to the relationship between the database tables.

       Shield differences between different database implementations. Hibernate only need to specify the currently used by the database in the form of "tongues", it can generate SQL statements for the actual situation of the underlying database.

       Non-invasive: Hibernate persistent classes are not required to implement any interface or inherit any class, POJO can.

       // reads the configuration file

                    Configuration conf=new Configuration().configure();

                    // create the configuration factory

                    SessionFactory sessionfactory=conf.buildSessionFactory();

                    // get the operation of the database session objects

                    Session session=sessionfactory.openSession();

                                

       It can be seen from Figure, the Hibernate the API a total . 6 , respectively, to : the Session , the SessionFactory , the Transaction , Query , Criteria and the Configuration .

Configuration class

Configuration categories: used to load the default configuration file (the file path of the hibernate.properties ).

              Call to configure () method will load the default file path xml configuration file format (hibernate.cfg.xml) is recommended.

If the profile does not default file path or the profile name does not comply with the default rule can be used

    new Configuration (). configure (file  ) to load the specified file

    new Configuration (). configure (path  ) to load files in the specified path

    If properties configuration file format, may be used . AddClass ( entity class name .class) method may load map files.          

 

SessionFactory objects

SessionFactory objects :

    SessionFactory on behalf of database storage source. According to Hibernate create the corresponding database to store source profile.

    SessionFactory After the object is created, and Configuration objects no longer associated. Modify Configuration configuration file contains information, not to SessionFactory have any impact.  

    Get SessionFactory objects:

new Configuration().configure().buildSessionFactory();

     Cache object is large, it is called heavyweight object. SessionFactory stored for Hibernate configuration information, mapping metadata information. Heavyweight object.

 

Session Object

Session objects:  

    The session on behalf of the program and the database. Session provides a method of operating the various databases. It is lightweight objects.

Gets Session Object

    factory.openSession (): get a new Session instance.

factory.getCurrentSession (): this method creates the Session will remove the current thread Session , using the underlying ThreadLocal access  

save () method : the Java object is saved to the database.

Transaction ts=session.beginTransaction();

User u=new User();

u.setName("赵六")

u.setPassword("123456")

// Save the object to the database                                  

session.save(u);                               

ts.commit();

update () method: update the database approach

Transaction ts=session.beginTransaction();

 // first find the object you want to modify, according to the primary key values                                      

User user=session.get(User.class, 1);                                  

user.setName("jery");                                  

 // object to update the database, according to OID                                  

session.update(user);                                     

ts.commit();

delete () method: Delete method

According to the underlying OID be deleted. There are two ways

1                                       

Transaction ts=session.beginTransaction();                                     

User user=session.get(User.class, 1);                                        

//删除指定对象                                       

session.delete(user);                                        

ts.commit();

2                                                                          

Transaction ts=session.beginTransaction();

User user=new User();                                       

user.setId(2);                                                                              

 session.delete(user);                                       

ts.commit();    

load()get()方法:从数据库查找指定对象

session.get(实体类名.class,OID);

session.load(实体类名.class,OID);

 

load()get()的区别:

                                                                                                                                                          我们使用get查询时发现控制台会立马打出查询语句。

使用load查询时控制台不会打印查询语句。

get方法被调用时立刻发送sql语句到数据库进行查询。

load方法被调用时并没有查询数据库,当我们需要使用查询的对象时,才去查询,所以当我们打印对象时,才会在控制台打印sql语句。

get()的原理

    程序调用get方法,Hibernate发送sql语句到数据库

数据库返回结果,Hibernate将结果封装成对象,返回对象到程序。

load()的原理

    程序调用load方法,Hibernate使用代理技术,创建一个代理对象,属性只有ID值。

    然后返回代理对象给程序,我们使用对象时,代理对象调用Hibernate查询数据库,初始化其他属性。

    load方法,返回一个代理对象,获取其属性时,会查询数据库,每次访问属性都会查询数据库么?

    答:不是。代理对象中有一个标识是否被初始化的boolean类型变量,记录是否被初始化。

查询所有对象的方法

    使用HQL语言(后面会详细介绍),HQL语言是面向对象的

     Query query=session.createQuery("from User");

      第二种方式

      Criteria c=session.createCriteria(User.class);

      List<User> l=c.list();

      第三种方式,使用原生sql语句进行查询

      SQLQuery query=session.createSQLQuery("select * from user");

      List l=query.list();

Transaction对象

    封装了事务的操作。我们做增删改查等操作时,必须开启事务.

    因为session是线程不安全的,这样主要是为了线程安全。保证数据的正确性。

    开启事务: Transaction ts=session.beginTransaction();

    提交事务:ts.commit();

    回滚事务:ts.rollback();

    当通过getCurrentSession获取当前线程绑定的Session时,事务关闭时,会自动把Session关闭并删除。

Query对象

     封装HQL语句的对象。

     返回一个对象的方法 query.uniqueResult();

     分页相关

     query.setFirstResult(index):从第几个取

     query.setMaxResults(count):指定取几行记录

https://blog.csdn.net/Vpn_zc/article/details/82784003(hibernate缓存)

综合自:https://blog.csdn.net/c99463904/article/details/72794787

         https://blog.csdn.net/jiuqiyuliang/article/details/39078749

发布了14 篇原创文章 · 获赞 1 · 访问量 5530

Guess you like

Origin blog.csdn.net/Vpn_zc/article/details/82783888