Hibernate Study Notes: Example 1

Source: Internet
Author: User

After learning hibernate again, I decided to share my study notes.
Create a project named hibernate. You can create a common Java project. Import jar packages. hibernate depends on many jar packages. I list all the jar packages used, including but not limited to these. I will not explain what these jar packages are. Because I used sqlserver 2000, the database driver msbase. jar, MSSQLServer. jar, msutil. jar files need to be copied in. If other databases are used, replace the files. Another strange thing is that hibernate depends on JTA. jar. these jar packages are available everywhere. If you want to centralize download, go to hibernate.org to download the latest all-inclusive hibernate-distribution-3.3.2.GA.


Create a new package Dao In the src directory and put all DaO interfaces in it. Create a new package Dao. hibernate implementation class for the DaO interface, sessionfactory,

Hibernate. cfg. xml. Create a package model to store all pojo and HBM ing files. The src directory looks like this:


Create hibernatesessionfactory. Java in Dao. hibernate:
Package Dao. hibernate; <br/> Import Org. hibernate. hibernateexception; <br/> Import Org. hibernate. session; <br/> Import Org. hibernate. cfg. configuration; </P> <p> public class hibernatesessionfactory {<br/> Private Static string config_file_location = "/Dao/hibernate. cfg. XML "; <br/> Private Static final threadlocal = new threadlocal (); <br/> Private Static final configuration CFG = N EW configuration (); <br/> Private Static Org. hibernate. sessionfactory; <br/> Public static session currentsession () throws hibernateexception {<br/> session = (Session) threadlocal. get (); <br/> If (session = NULL |! Session. isopen () {<br/> If (sessionfactory = NULL) {<br/> try {<br/> cfg. configure (config_file_location); <br/> sessionfactory = cfg. buildsessionfactory (); <br/>}catch (exception e) {<br/> system. err. println ("% error creating sessionfactory %"); <br/> E. printstacktrace (); <br/>}< br/> session = (sessionfactory! = NULL )? Sessionfactory. opensession (): NULL; <br/> threadlocal. set (session); <br/>}< br/> return session; <br/>}< br/> Public static void closesession () throws hibernateexception {<br/> session = (Session) threadlocal. get (); <br/> threadlocal. set (null); </P> <p> If (session! = NULL) {<br/> session. close (); <br/>}< br/> private hibernatesessionfactory () {<br/>}</P> <p>

In Dao. hibernate. cfg. XML: If it is sqlserver2005, the driver name is different: COM. microsoft. sqlserver. JDBC. sqlserverdriver, which is a poor problem.
<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <! Doctype hibernate-configuration Public <br/> "-// hibernate/hibernate configuration DTD 3.0/EN" <br/> "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <br/> <pibernate-configuration> <br/> <session-factory> <br/> <property name = "dialect"> Org. hibernate. dialect. sqlserverdialect </property> <br/> <! -- JDBC --> <br/> <property name = "connection. URL "> JDBC: sqlserver: // localhost: 2431; databasename = hibernate </property> <br/> <property name =" connection. driver_class "> COM. microsoft. JDBC. sqlserver. sqlserverdriver </property> <br/> <property name = "connection. username "> SA </property> <br/> <property name =" connection. password "> 123456 </property> </P> <p> <property name =" JDBC. fetch_size "> 50 </property> <br/> <property name =" JDBC. batch_size "> 30 </property> <br/> <property name =" show_ SQL "> true </property> <br/> <property name =" format_ SQL "> false </ property> </P> <p> <property name = "connection. autocommit "> true </property> <br/> <property name =" current_session_context_class "> thread </property> </P> <p> <Mapping Resource =" model/book. HBM. XML "/> <br/> </session-factory> <br/> </pibernate-configuration> </P> <p>

A basehibernatedao:
Package Dao. hibernate; <br/> Import Org. hibernate. session; <br/> public class basehibernatedao {<br/> // This class is very simple, that is, the session of the current thread is returned from hibernatesessionfactory <br/> public session getsession () {<br/> return hibernatesessionfactory. currentsession (); <br/>}</P> <p>}

Create pojo book. Java:
Public class book {<br/> private string ID; <br/> private string name; <br/> private string author; <br/> private float price; </P> <p> Public book () {}; <br/> Public book (string ID, string name, string author, float price) {<br/> This. id = ID; <br/> This. name = Name; <br/> This. author = author; <br/> This. price = price; <br/>}< br/> // carry tostring to facilitate testing. <br/> Public String tostring () {<br/> return "{ID:" + ID + "/nname:" + name + "/nauthor: "+ author +"/nprice: "+ Price + "}"; <br/>}< br/> // getter and setter ignored <br/>}</P> <p>

You need a database for testing. In any case, learning the hibernate database is required. I use sqlserver2000 at home, and my new database name is hibernate.

Create a book ing file book. HBM. xml under the model: It is worth noting that if the database has a schema, do not forget to add the schema and catalog (database name)
This file is followed by a DML table creation statement.
 <? XML version = "1.0" encoding = "UTF-8"?> <Br/> <! Doctype hibernate-mapping public "-// hibernate/hibernate mapping DTD 3.0 // en" <br/> "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> </P> <p> <pibernate-mapping package = "model"> <br/> <class name = "book" table = "book" schema = "DBO" catalog = "hibernate"> <br/> <ID name =" ID "column =" ID "> <br/> <generator class =" UUID "/> <br/> </ID> <br/> <property name =" name" /> <br/> <property name = "author"/> < Br/> <property name = "price"/> <br/> </class> <br/> </pibernate-mapping> <br/> <! -- <Br/> Create Table Book (<br/> ID int identity (1, 1) primary key, <br/> name varchar (20) not null, <br/> author varchar (20), <br/> price float <br/>) <br/> --> </P> <p>
A bookhibernatedao. Java: Is the implementation class of bookdao. It is worth noting that the class contains test case.
Package Dao. hibernate; <br/> Import Java. util. list; <br/> Import Org. hibernate. transaction; <br/> Import model. book; <br/> Import Dao. bookdao; </P> <p> public class bookhibernatedao extends basehibernatedao implements bookdao {</P> <p> public list <book> List () {<br/> return getsession (). createquery ("from book "). list (); <br/>}</P> <p> Public book findbyid (string ID) {<br/> return (book) getsession (). get (book. class, ID); <br/>}</P> <p> Public void save (Book) {<br/> // transaction Tx = getsession (). begintransaction (); <br/> getsession (). saveorupdate (book); <br/> getsession (). flush (); <br/> // Tx. commit (); <br/>}</P> <p> Public void Delete (string ID) {<br/> book B = (book) getsession (). load (book. class, ID); <br/> // transaction Tx = getsession (). begintransaction (); <br/> getsession (). delete (B); <br/> // Tx. commit (); <br/>}< br/> // test case <br/> Public static void main (string [] ARGs) {<br/> bookdao Dao = new bookhibernatedao (); <br/> List <book> List = Dao. list (); <br/> system. out. println (list. size (); <br/> for (book B: List) {<br/> system. out. println (B); <br/>}< br/> book B = New Book (null, "book name", "book author", 11.5f ); <br/> Dao. save (B); <br/>}< br/>}

Run bookhibernatedao to test whether hibernate can run normally. If no error occurs, print all the books.
Here are several questions:
1This Syntax of hibernatesessionfactory is automatically generated by myeclipse. If you have myeclipse, you can also automatically generate hibernatesessionfactory and hibernate. cfg. XML, pojo, HBM. XML and Dao, but I think it is best to write them all, including the configuration file. when I went out for an interview, someone asked me how to configure the attributes? Why? Have you heard of it ~? I personally think that hibernatesessionfactory is well written. It uses threadlocal to associate the session with the current thread, solving the thread security issue of the session.
2In the SAVE and delete methods in bookhibernatedao, I deregistered the transaction items, thanks to the configuration in hibernate. cfg. xml:
<Property name = "connection. autocommit "> true </property>, which means connection. setautocommit (true); if you have not configured connection. autocommit = true; The transaction needs to be explicitly committed in the program; many new users have asked this question. However, even if autocommit is configured, do not forget getsession (). flush (); why is this sentence called? In the source code, force this session to flush. must be called at the end of a unit of work, before commiting the transaction and closing the session; the addition, deletion, and modification of the session object are all temporarily marked in the session. After flush is called, the session will be synchronized with the database.
3About ID: In the world of hibernate, identifying an object depends on ID. In this example, UUID is used to automatically generate a 32-bit string type ID. UUID is flexible and does not depend on databases, but it is a waste of space. You can also replace it with an int ID,
Create Table Book (
Id int identity (1, 1) primary key,
Name varchar (20) not null,
Author varchar (20 ),
Price float
)
You can use the identity or native generator <generator class = "Identity"/>. If it is an Oracle database and uses sequence as the ID generator, you can select sequence, <generator class = "sequence"> <Param name = "sequence"> sequence name </param> </generator>.

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.