<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by fengqi xiao on Medium]]></title>
        <description><![CDATA[Stories by fengqi xiao on Medium]]></description>
        <link>https://medium.com/@xiaofq51?source=rss-bd1fcde7c25d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ilrMZGfTCLu8CGlp.</url>
            <title>Stories by fengqi xiao on Medium</title>
            <link>https://medium.com/@xiaofq51?source=rss-bd1fcde7c25d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:48:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xiaofq51/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using Hibernate in NetBeans — 2]]></title>
            <link>https://medium.com/@xiaofq51/using-hibernate-in-netbeans-2-153794acea9f?source=rss-bd1fcde7c25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/153794acea9f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[ssh]]></category>
            <dc:creator><![CDATA[fengqi xiao]]></dc:creator>
            <pubDate>Thu, 08 Mar 2018 22:47:36 GMT</pubDate>
            <atom:updated>2018-03-08T22:47:36.043Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post, I have introduced how to configure environment for Hibernate in NetBeans with a simple example. It is a good start, but not enough to use Hibernate in our project.</p><p>In this post, I am gonna talk about using Hibernate classes/methods to work with database, such as Session, HQL. And also with the example code.</p><h3>Session</h3><p>session is an important class that is used to connect the database and retrieve data. In order to accomplish query and DML statements for our data, we have to know how to use methods associate to session.</p><p>Here is a simple example below.</p><pre>public class NoteDB {</pre><pre>// Create session object from hibernate package    <br>Session session = null;</pre><pre>public NoteDB() {</pre><pre>Session session = null;<br>        Transaction tx = null;<br>        List&lt;Note&gt; notelist = null;<br>        try {<br>            session = session =          NoteUtil.getSessionFactory().openSession();<br>            notelist = null;<br>            tx = session.beginTransaction();<br>            Query query = session.createQuery(&quot;from Note&quot;);<br>            notelist = query.list();<br>            tx.commit();<br>            System.out.println(notelist.size());<br>        } catch (HibernateException e) {<br>            if (tx != null) {<br>                tx.rollback();<br>            }<br>            e.printStackTrace();<br>        }<br>        finally {<br>         session.close(); <br>      }<br>        return notelist;</pre><p>In the example code, we can clearly see the logic of using session. First, create a session object, and then assign the connection in the constructor. Next, when starting the transaction in target method, need to specify session.beginTransaction(). Last, query the database and save the retrieved data.</p><p>Need to know the difference between using getCurrentSession and openSession</p><h4>SessionFactory</h4><p>SessionFactory configure the Hibernate configuration file which is <em>hibernate.cfg.xml </em>to create session object.</p><p>Need to know that Hibernate provides a function to generate utility class to create this SessionFactory. The code below is my sample utility class. Notice that there are some code being commented out because they are deprecated for the Hibernate version 4.3.x. They could still work, but if you want the best efficiency, you need to find out the code for your version.</p><pre>public class NoteUtil {</pre><pre>private static final SessionFactory sessionFactory;</pre><pre>static {<br>        <br>// Create the SessionFactory from standard (hibernate.cfg.xml)config file.</pre><pre>//sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); </pre><pre>//sessionFactory = new Configuration().configure().buildSessionFactory();<br>            <br>Configuration configuration = new Configuration();<br>            configuration.configure();<br>            <br>ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(<br>            configuration.getProperties()).build();<br>            <br>sessionFactory = configuration.buildSessionFactory(serviceRegistry);<br>        <br>    }</pre><pre>public static SessionFactory getSessionFactory() {<br>        return sessionFactory;<br>    }<br>}</pre><h4>Transaction</h4><p>Transaction interface is responsible for controlling database transaction. It , allows the application to define units of work. There some methods we need to know and use in our application, such as begin(), commit(), and rollback().</p><h4>CRUD</h4><p>Session interface also provides function to create, read, update, and delete data from database.</p><pre>//  Persist the given transient instance, first assigning a generated identifier.<br>  <strong>Serializable save(Object object)</strong> </pre><pre>//  Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance.<br>  <strong>Session get(String entityName, Serializable id)</strong></pre><pre>//  Update the persistent instance with the identifier of the given detached instance.<br>    <strong>void update(Object object)</strong></pre><pre>//   Remove a persistent instance from the datastore.<br>    <strong>void delete(Object object)</strong></pre><p>However, in our sample code, we use createQuery() which use HQL to retrieve data from database. This function is very similar to get() method. They all retrieve data from database, and construct to the object, and return the result. The differences are that get() needs identifier to return a single object, and createQuery() will modify the data by different HQL.</p><pre>Query query = session.createQuery(&quot;from Note&quot;);</pre><h3><strong>HQL</strong></h3><p>HQL-Hibernate Query Language-is an object-oriented query language. The syntax of HQL is very similar to SQL, it manipulate the Java objects instead of database tables. There are some useful HQL clause you may wanna use to query your database.</p><h4>FROM CLAUSE</h4><p>FROM clause is the basic clause used in HQL. In our sample code, ‘<strong>Note</strong>’ is not the table name in database. Actually, it is the domain class name. Since we already create the mapping file to map between tables and classes, Hibernate will query the specific table based on the class and attribute in it.</p><pre>Query query = session.createQuery(&quot;from Note&quot;);</pre><h4>SELECT CLAUSE</h4><p>SELECT clause provide more concise control rather than FROM clause. It allows you to choose the attributes of the object. For the example shows below. This query statement will return a list of Note object with only one <strong><em>noteId </em></strong>field.</p><pre>Query query = session.createQuery(&quot;SELECT Note.noteId FROM Note&quot;);</pre><h4>WHERE CLAUSE</h4><p>we can also use where clause to restrict the result the same as SQL WHERE clause. In the sample code below, the first <em>noteId </em>means the attribute in the <em>Note</em> class, and the second <em>noteId</em> is used to set the value to search.</p><pre>Query query = session.createQuery(&quot;FROM Note WHERE noteId = :noteId&quot;);</pre><p>Those are all basic concept for Hibernate. If you wanna use this framework in your project, you need to learn deeper than what I show you here. Rather than that, there are also some other useful functions in Hibernate, such as i<strong>nterceptor, batch process, and cache mechanism. </strong>Understand those concepts will help you implement great project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=153794acea9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Hibernate in NetBeans — 1]]></title>
            <link>https://medium.com/@xiaofq51/using-hibernate-in-netbeans-1-574637ccc035?source=rss-bd1fcde7c25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/574637ccc035</guid>
            <category><![CDATA[netbeans]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[hibernate]]></category>
            <dc:creator><![CDATA[fengqi xiao]]></dc:creator>
            <pubDate>Fri, 23 Feb 2018 01:35:19 GMT</pubDate>
            <atom:updated>2018-03-07T17:43:43.715Z</atom:updated>
            <content:encoded><![CDATA[<p>As we know, the architecture of Hibernate has different layers. Programmers no need to know lower level API. Instead, they can focus on persistence layer.</p><p>In order to provide useful information, my system configuration list below:</p><p><strong>Windows 10, NetBeans IDE 8.2, Hibernate 4.3.1</strong></p><p>There is a good picture illustrate perfect application schema view of Hibernate architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*KZgoNe0xAObqe4jlmS0Meg.jpeg" /></figure><p>Another picture shows application architecture of Hibernate and some important class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*2ouOVKlMZBid1Ygk-SC9PQ.jpeg" /></figure><h3>Import/Install</h3><p>Before start using Hibernate, you need to import it into your project. In NetBeans, when you create a new web application project, it will prompt users to select build-in frameworks, such as <strong>Spring Web MVC, JavaServer Faces, Struts and Hibernate</strong>. If you don’t have the option to add Hibernate Framework, you can also download it by going to <a href="http://hibernate.org/orm/downloads/">Hibernate official website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*0sYXIWM9o8uVnDsJ6AQdFA.png" /></figure><p>Now you can start using Hibernate in you project!</p><h3>Configuration</h3><p>In the first image above, it shows that there are two important files in Hibernate. They are all used to configure Hibernate environment.</p><p>First of all, need to configure Hibernate.properties which is <strong>hibernate.cfg.xml </strong>located in <strong>Source Package</strong>. In this file, there are several properties must be configured properly.</p><p>During the creation of new web application, Database connection and dialect need to be set, so in the default <strong>hibernate.cfg.xml </strong>file, some properties are already configured. Only one property need to add at the moment is <strong><em>hibernate.current_session_context_class. </em></strong>in my case, I have to set ‘Thread ’ to it, otherwise ‘SessionFactory’ will not work.</p><pre>&lt;hibernate-configuration&gt;<br> &lt;session-factory&gt;<br><strong><em>&lt;!-- set SQL dialect using in Hibernate to query DB--&gt;</em></strong><br>  &lt;property name=&quot;hibernate.dialect&quot;&gt;<br>   org.hibernate.dialect.MySQLDialect<br>  &lt;/property&gt; <br><strong><em>&lt;!-- Database connection --&gt;</em></strong><em><br></em>  &lt;property name=&quot;hibernate.connection.driver_class&quot;&gt;<br>   com.mysql.jdbc.Driver<br>  &lt;/property&gt;<br>  &lt;property name=&quot;hibernate.connection.url&quot;&gt;<br>   jdbc:mysql://localhost:3306/notesdb<br>  &lt;/property&gt;<br>  &lt;property name=&quot;hibernate.connection.username&quot;&gt;root&lt;/property&gt;<br>  &lt;property name=&quot;hibernate.connection.password&quot;&gt;password&lt;/property&gt;     <strong><em>&lt;!-- must set this property to &#39;thread&#39; otherwise not working--&gt;</em></strong><br>   &lt;property name=&quot;hibernate.current_session_context_class&quot;&gt;<br>   thread<br>  &lt;/property&gt;<br><strong><em>&lt;!--set mapping configuration file--&gt;<br>&lt;!--this will auto generate later in the article--&gt;</em></strong>  <br> &lt;mapping resource=&quot;domainmodel/Note.hbm.xml&quot;/&gt;<br> &lt;/session-factory&gt;<br>&lt;/hibernate-configuration&gt;</pre><p>Then, it is time to provide mapping function between DB tables and domain classes. We need to create a ‘Hibernate Reverse Engineering’ file. It is a XML file used to modify tables and schema in Database that will map to Java domain classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*SgPydd6gPmAZmLkOVlGpsQ.png" /></figure><p>The image above shows how the wizard looks like. Programmers can simply select and deselect tables between ‘<strong><em>Available Tables</em></strong>’ fields and ‘<strong>Selected Tables</strong>’. Click finish button, the reverse engineering file, <strong><em>hibernate.reveng.xml, </em></strong>will be created automatically in the same directory as Hibernate .properties configuration file.</p><pre>&lt;hibernate-reverse-engineering&gt;<br> &lt;schema-selection match-catalog=&quot;notesdb&quot;/&gt;<br> &lt;table-filter match-name=&quot;note&quot;/&gt;<br>&lt;/hibernate-reverse-engineering&gt;</pre><p>Now, it is time to work on domain classes. Hibernate provide functions to map files and POJOs from database. Open the wizard, it will looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*JchuUqUUzwghU8kqEJ8vNQ.png" /></figure><p>In the wizard,</p><ul><li>At the top, there are two drop-down lists to select hibernate configuration file and reverse engineering file. Each type of file is unique in one project, and they are selected by default.</li><li>In General Setting, there are JDK 5 language feature and EJB 3 Annotations. Choosing EJB 3 Annotations generate POJOs with annotations.</li><li>In Code Generation Setting, both check boxes are checked by default and we need them.</li><li>Project is the one in developing.</li><li>Location is setting to Source Package.</li><li>For Package, we must to choose a package/folder in the drop-down list to store the .hmb.xml and .java files.</li><li>After clicking finish button, Hibernate mapping files and POJOs are generated in the selected folder.</li><li>and Hibernate configuration file also updated.</li></ul><pre><strong><em>&lt;!--set mapping configuration file--&gt;<br></em></strong>&lt;mapping resource=&quot;domainmodel/Note.hbm.xml&quot;/&gt;</pre><h3>Initialize SessionFactory</h3><p>In order to modify database, we need to use SessionFactory class to achieve this goal. According to the documentation of SessionFactory.class</p><blockquote><em>“Creates Sessions. Usually an application has a single SessionFactory. Threads servicing client requests obtain Sessions from the factory.”</em></blockquote><p>In NetBeans, Hibernate provides functions to generate SessionFactory very easy. Just needs to type in Class name and select Package, and click Finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*X69b5R7NvWIsPGBwBjujzQ.png" /></figure><p>The code generated shows blow. To call getSessionFactory method in order to use, and the class</p><pre>public class NoteUtil {</pre><pre>private static final SessionFactory sessionFactory;<br> <br> static {<br> try {<br> // Create the SessionFactory from standard (hibernate.cfg.xml) <br> // config file.<br> sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();<br> } catch (Throwable ex) {<br> // Log the exception. <br>System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);<br> throw new ExceptionInInitializerError(ex);<br> }<br> }<br> <br> public static SessionFactory getSessionFactory() {<br> return sessionFactory;<br> }<br>}</pre><h3>Query Database</h3><p>Now, we are able to manage our data through Hibernate. Here is a simple example based on the whole configuration process. This code is to retrieve all the data in Note table. Hibernate uses <strong>HQL </strong>to query the database. It is very similiar to SQL but slightly different. More details will come in next post.</p><pre>public class NoteDB {<br> Session session = null;</pre><pre>public NoteDB() {<br> this.session = NoteUtil.getSessionFactory().getCurrentSession();<br> }<br> <br> public List getAllNotes()<br> {<br>     List&lt;Note&gt; notelist = null;<br>     Transaction tx = session.beginTransaction();<br>     Query query = session.createQuery(&quot;from Note&quot;);<br>     notelist = query.list();<br>     return notelist;<br> }<br>}</pre><p>Overall, there are three parts introduced in this blog, such as Import&amp;install, Configuration and Initializing connection. In my next blog, I will introduce HQL, annotations, caching and batch processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574637ccc035" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intro to Hibernate]]></title>
            <link>https://medium.com/@xiaofq51/intro-to-hibernate-6cd75238e24b?source=rss-bd1fcde7c25d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cd75238e24b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[junior-developer]]></category>
            <dc:creator><![CDATA[fengqi xiao]]></dc:creator>
            <pubDate>Sun, 28 Jan 2018 05:43:09 GMT</pubDate>
            <atom:updated>2018-01-28T05:43:09.860Z</atom:updated>
            <content:encoded><![CDATA[<p>Hibernate as we all know is one of the most popular SSH frameworks. The other two are Struts and Spring framework.</p><ul><li>Struts uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller (MVC) architecture.</li><li>The Spring Framework is an application framework and inversion of control container for the Java platform.</li></ul><p>The image is showing the relation of three frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*WJvgiBsVvzcqBapm4atmiw.png" /></figure><p>Using Hibernate can help us get rid of the rigid operations of JDBC. Actually, it provides mapping function between Java domain model to a relational database. By using Hibernate, operations for database can be easier and more convenient. After configuration, we are able to use this framework to manipulate the database.</p><h3><strong>What is Hibernate?</strong></h3><p>Hibernate is ORM framework for Java programming language. ORM stands for object-relational mapping. The key point is Hibernate help us map Entity, also called Bean or POJO(Plain Ordinary Java Object), which is from object-oriented programming design to database tables which are relational database design.</p><h3><strong>JPA</strong></h3><p>JPA stands for Java Persistence API, it is actually specification. and Hibernate is the implementation of JPA specification. One is interface standard, another one is specific implementation.</p><p>So why JPA? First, it is easy to use. Help developers increase the efficiency for the project. Second, it is easy to maintain, and reduce the cost. Instead of working away with JDBC and database, developers can simply work Java domain class. Last, compare with JDBC, it may needs less time to learn and use.</p><p>Even though it seems easy and simple to learn and use, there are some weak points we also need to know. First, the combination of using Java class and database is a good way to get rid of database, but if data changes, we need to take more effort in renewing the configuration files. Second, when the amount of data is very high, the performance may be unsatisfied. Last, compare traditional development technology, it is even harder to find what the bug is.</p><h3>Differences between Hibernate and <strong>EclipseLink</strong></h3><p><strong>EclipseLink</strong> is the open source Eclipse Persistence Services Project from the Eclipse Foundation. It also supports JPA.</p><p>There is a article published in 2008 that compares 4 popular JPA implementations. In here, why I only talk about Hibernate and EclipseLink<strong>? </strong>Because I have used EclipseLink for some simple projects, and Hibernate is my current focus.</p><p>It is a fixed-time test in the same system environment, and tester monsters memory usage, CPU usage and total executing times. All the ORMs are executing the same query and insertion statements.</p><p>Based on his test, the results display some interesting information. First of all, Hibernate has finished outstandingly more statements than any other ORMs. However, it also requires more memory usage. Obviously, it prestore some key data to the memory, so when it needs the data, it can take it from memory. This operation is much faster than query database. Second, the performance for EclipseLink is overall average, but CPU usage is pretty low.</p><p>According to the result of test, Hibernate is more suitable for a project that requires more query and DML operations. Compare with Hibernate, EclipseLink is lightweight. It needs less resources to perform lower performance.</p><p>The original article for test is <a href="http://terrazadearavaca.blogspot.ca/2008/12/jpa-implementations-comparison.html">here</a>. It would be nice to run the test case again cause it has been 10 years!</p><h3>Advantage</h3><p>One of the biggest advantage is that Hibernate keep all data operations in persistence layer, so developers can focus on Java objects instead of JDBC or database. The popular database nowadays is still relational database, but Java is object-oriented programming language. Therefore, different data structures always cause difficulties in their relations. Hibernate, and also other ORMs, help developers solve this problem. It supports mapping between Java objects and database tables. Let developers use object-oriented thinking to solve problems.</p><p>In term of XML configuration mechanism, Hibernate has good portability. By using Hibernate, developers no need to care about different databases used for projects. However, JDBC is slightly different.</p><p>Then, Hibernate provide a great encapsulation of database-it is also a disadvantage.A lot of data operations are well encapsulated. Developers no need to code that much SQL codes, so they are able to work more efficiently.</p><p>Hibernate provides three types of caching, Session Cache, Second Level Cache and Query Cache. For the data that are not often to change but always to use, saving into cache may be a smart solution. Caching can greatly benefit performance.</p><h3>Disadvantage</h3><p>The biggest problem of Hibernate is also encapsulation of JDBC. It is not flexible, even hard to optimized. For some complex query statements, it is difficult to say, Hibernate performs better than using JDBC directly.</p><p>Another problem is from caching. In order to use cache mechanism, Hibernate asks more memory usage. Moreover,for every mapping and query operations, Hibernate instantiate objects in order to accomplish the operation. So in some cases, the usage of memory might be exaggerated.</p><p><strong>Overall,</strong> Hibernate is a great framework to use by Java developers. Although it has pros and cons, every coin has two faces.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cd75238e24b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>