A simple Hibernate tutorial
I have found a lot of Hibernate related tutorials on the Internet. Most of them are based on WEB servers, and I write a separate
In Eclipse, you do not need to write your own ANT script, and do not need to use the web server. However, MYSQL database-_-is required -_-
First, you must learn how to use Eclipse, then download all the JAR files required by Hibernate, and finally install MYSQL
Preparations start!
Step 1: Create a table structure as follows:
+ ----------- + -------------- + ------ + ----- + --------- + ---------------- +
| Field | Type | Null | Key | Default | Extra |
+ ----------- + -------------- + ------ + ----- + --------- + ---------------- +
| Id | int (11) | NO | MUL | NULL | auto_increment |
| Title | varchar (400) | YES | NULL |
| Content | text | YES | NULL |
| Time | datetime | YES | NULL |
+ ----------- + -------------- + ------ + ----- + --------- + ---------------- +
Step 2: Create a JAVA project in Eclipse (the package name I used in the project is cn.com. nick. hbm ). Compile the News. java class, which corresponds to the table in the database
Package cn.com. nick. hbm;
Import java. util. Date;
Public class News
{
Private int id;
Private String title;
Private String content;
Private Date date;
Public int getId ()
{
Return id;
}
Public void setId (int id)
{
This. id = id;
}
Public String getTitle ()
{
Return title;
}
Public void setTitle (String title)
{
This. title = title;
}
Public String getContent ()
{
Return content;
}
Public void setContent (String content)
{
This. content = content;
}
Public Date getDate ()
{
Return date;
}
Public void setDate (Date date)
{
This. date = date;
}
}
Step 3: Save the configuration correspondence as the News. hbm. xml file and the News class in the same directory (not necessarily in the same directory, so that you can put them here for convenience)
<? Xml version = "1.0"?>
<! DOCTYPE hibernate-mapping PUBLIC
"-// Hibernate/Hibernate Mapping DTD 3.0 // EN"
Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd>
<Hibernate-mapping>
<! -- The cn.com. nick. hbm. News class corresponds to the NEWS table -->
<Class name = "cn.com. nick. hbm. News" table = "NEWS">
<! -- From here, the attribute in the News class is configured to correspond to the field in the table and the type of this field -->
<Id name = "id" column = "id">
<Generator class = "native"/>
</Id>
<Property name = "title" type = "string" column = "TITLE"/>
<Property name = "content" type = "string" column = "CONTENT"/>
<Property name = "date" type = "timestamp" column = "TIME"/>
</Class>
</Hibernate-mapping>
Step 4: Configure hibernate. cfg. xml note that this name cannot be changed and should be placed under the path of SRC (note that the method in the example of the wrong place cannot find this file)
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE hibernate-configuration
PUBLIC "-// Hibernate/Hibernate Configuration DTD // EN"
Http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd>
<Hibernate-configuration>
<Session-factory name = "java:/hibernate/HibernateFactory">
<Property name = "show_ SQL"> true </property> <! -- Configure to display SQL statements for debugging -->
<Property name = "connection. driver_class">
Com. mysql. jdbc. Driver <! -- The JDBC driver class Name of mysql -->
</Property>
<Property name = "current_session_context_class"> thread </property> <! -- Configuration context -->
<Property name = "connection. url">
Jdbc: mysql: // localhost: 3306/test <! -- Here is the URL of the mysql hibernate_test database -->
</Property>
<Property name = "connection. username"> root </property> <! -- Username -->
<Property name = "connection. password"> 123 </property> <! -- Password -->
<Property name = "dialect">
Org. hibernate. dialect. MySQLDialect <! -- Here is mysql Dialect -->
</Property>
<Property name = "myeclipse. connection. profile"> my </property>
<Mapping resource = "cn/com/nick/hbm/News. hbm. xml"/> <! -- Specify the ing file of News -->
</Session-factory>
</Hibernate-configuration>
The code for creating a Test. java class is as follows, which contains annotations.
Package cn.com. nick. hbm;
Import java. util. Date;
Import java. util. List;
Import org. hibernate. HibernateException;
Import org. hibernate. SessionFactory;
Import org. hibernate. cfg. Configuration;
Import org. hibernate. classic. Session;
Public class Test
{
Private static final SessionFactory sessionFactory;
Static
{
Try
{
// SessionFactory is created here to put the hibernate. cfg. xml file to the path of SRC.
// Hibernate will find it by yourself
SessionFactory = new Configuration (). configure ()
. BuildSessionFactory ();
} Catch (Throwable ex)
{
// Make sure you log the exception, as it might be swallowed
System. err. println ("Initial SessionFactory creation failed." + ex );
Throw new ExceptionInInitializerError (ex );
}
}
Public static SessionFactory getSessionFactory ()
{
Return sessionFactory;
}
Public static void main (String [] args)
{
// Instantiate a new News object and fill in the content
News news = new News ();
News. setTitle ("test title ");
News. setContent ("add Test content ");
News. setDate (new Date ());
Test t = new Test ();
// Call the storage method under the Test class, which is equivalent to executing the INSERT statement
// T. Save (news );
// Call the query method to display the database content
T. select ();
// Call the update Method
// T. update ();
// Call Delete
// T. delete ();
}
/**
* A Simple Method for adding data
* @ Param news object, which will be added to the library
*/
Public void Save (News news)
{
Try
{
// Obtain the hibernate session
Session session = Test. getSessionFactory (). getCurrentSession ();
Session. beginTransaction ();
// Here, you only need to call the save method to upload the news object and insert it successfully!
Session. save (news );
Session. getTransaction (). commit ();
} Catch (HibernateException e)
{
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
/**
* Query Method
*/
Public void select ()
{
Try
{
Session session = Test. getSessionFactory (). getCurrentSession ();
Session. beginTransaction ();
// Note !!! The News here is not the table name! It is the object name, so pay attention to Case sensitivity.
String SQL = "from News ";
// Conditional Query
// String SQL = "from News where id = 1 ";
// Use session. createQuery () to execute the HQL query statement
List <News> l = session. createQuery (SQL). list ();
// Cyclically output in the console
For (News n: l)
{
System. out. println (n. getId ());
System. out. println (n. getTitle ());
System. out. println (n. getContent ());
System. out. println (n. getDate ());
System. out. println ("================ ");
}
Session. getTransaction (). commit ();
} Catch (HibernateException e)
{
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
/**
* Update Method
*/
Public void update ()
{
Try
{
Session session = Test. getSessionFactory (). getCurrentSession ();
Session. beginTransaction ();
// Defines the ID of the object to be loaded
Integer id = 1;
// Load an object
News n = (News) session. load (News. class, new Integer (id ));
// Reset the object title
N. setTitle ("updated title ");
// Update this object using the update Method
Session. update (n );
Session. getTransaction (). commit ();
} Catch (HibernateException e)
{
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
Public void delete ()
{
Try
{
Session session = Test. getSessionFactory (). getCurrentSession ();
Session. beginTransaction ();
// Defines the ID of the object to be loaded
Integer id = 6;
// Load an object
News n = (News) session. load (News. class, new Integer (id ));
// Delete the object using the delete Method
Session. delete (n );
Session. getTransaction (). commit ();
} Catch (HibernateException e)
{
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
Okay. Run the Test class to check the effect!
Note: To run this example, you also need to import the MYSQL driver to the project. In addition, the import of the Hibernate jar file must be complete, hibernate uses many other JAR files which need to be imported to the project. Refer to this article.