Getting started with Hibernate (1)

Source: Internet
Author: User

It's all said that at the end of the year, everyone should be making a payment. It's busy. I had nothing to do with the three months I just turned around. I had to charge myself at work, and it was not fun. After all, not long after I came to the company, I was not so bold as those old birds, keep a low profile and start watching the video. The following is a simple record of what I learned. Today I watched the Hibernate learning video and summarized it myself. By the way, I can digest it:

I. Download Hibernate: Ghost (here I am using hibernate3). I don't know what the difference is with the current hibernate4 (I hope someone can give me a correction );
2. After the jar package is ready, you can create a new java project and import all the jar packages just now (of course not all jar packages are required, however, it is not clear which ones do not need to be imported in case of exceptions. For security reasons, please );
3. After the project is built, we can start our development exercises:
First, create a new hibernate under the src directory. cfg. xml file (as for why it is in the src directory, because the src directory will eventually be compiled to a bin folder, that is, the class path (under classpath ), when the server starts, it will find the file in classpath for parsing and loading );
Secondly, start to explain the hibernate. cfg. xml file configuration (I am connected to the MySQL5 database, here must import the mysql-connector-java.jar driver package ):

 
  
   
    
Com. mysql. jdbc. Driver
   
   
   
    
Jdbc: mysql: // test
   
   
   
    
Root
   
   
   
    
Root
   
   
   
    
Org. hibernate. dialect. MySQLDialect
   
   
   
    
Create
   
   
   
    
True
   
   
   
   
  
 

The above properties can all be found in the Hibernate. properties file under the etc folder in the previously downloaded hibernate decompression package (). Here we will explain hbm2ddl. auto (there are four values ):

Create: each time hibernate is loaded, the last generated table will be deleted, and then the new table will be re-generated based on your model class, even if there are no changes twice, it will be executed like this, this is an important cause of data loss in database tables.
Create-drop: each time hibernate is loaded, a table is generated based on the model class. However, when sessionFactory is disabled, the table is automatically deleted.
Update: The most common attribute. When hibernate is loaded for the first time, the structure of the table is automatically created based on the model class (the premise is that the database is created first). When hibernate is loaded, the table structure is automatically updated based on the model class, even if the table structure is changed, the row in the table still does not delete the previous row. Note that after the application is deployed to the server, the table structure will not be created immediately. It will not be created until the application runs for the first time.
Validate: verify whether the existing schema is consistent with the hibernate you configured at startup. If they are inconsistent, an exception is thrown and no updates are made.

4: now we can develop our entities:

User. java

Package toone.com.cn. bo; import java. util. date; public class User {private int id; // a primary key is required because the primary key idprivate String name; private Date birthday is required in many hibernate methods; // The default constructor must be provided. No constructor is provided here, but all classes have the default constructor;
public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}

User. hbm. xml (ing file)

 
  
   
   
    
    
   
   
   
   
  
 


5. Finally, we can develop our business (mainly for adding, deleting, modifying, and querying users ):

Previously, using jdbc to connect to a database is cumbersome. Here we have made full use of hibernate's convenience and advantages:

Main. java

Package toone.com.cn; import java. util. date; import org. hibernate. hibernateException; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; import toone.com.cn. bo. user; public class Main {public static void main (String [] args) {// do not write Configuration cfg = new Configuration (); otherwise, Hibernate Dialect must be explicitly s will be reported. The et error message will mislead us. // In fact, we have configured the mysql dialect before. Configuration cfg = new Configuration (). configure (); // For the configure () method, we can introduce its source code for viewing, it will automatically load a default hibernate under the class path // path. cfg. xml file; if you want to change other names, you can use its overload method. For details, see its source code (which is included in the downloaded compressed package) SessionFactory factory = cfg. buildSessionFactory (); User user User = new user (); User. setName ("Kobi"); user. setBirthday (new Date (); Session session = null; Transaction tx = null; try {session = factory. openSes Sion (); tx = session. beginTransaction (); // start the transaction session. save (user); // save tx. commit (); // commit transaction} catch (HibernateException e) {if (tx! = Null) {tx. rollback (); // rollback transaction} throw e; // an exception must be thrown} finally {if (session! = Null) {session. close (); // close session }}}}

All right, the addition function has been implemented. But here, we may find that each operation, such as adding, modifying, deleting, and searching, needs to execute this Code:

Configuration cfg = new Configuration().configure();SessionFactory factory = cfg.buildSessionFactory();

This code is very performance-consuming, because it needs to load the parsing configuration file hibernate every time. cfg. xml, and the session needs to be created each time. Therefore, we may create a tool class by ourselves, which is implemented in a single-profit manner, and the tool class implements addition, deletion, modification, and query of objects. The Code is as follows:

HibernateUtils. java

Package toone.com.cn. util; import java. io. serializable; import org. hibernate. hibernateException; import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. transaction; import org. hibernate. cfg. configuration; public class HibernateUtils {private static SessionFactory sessionfactory; private HibernateUtils () {}static {Configuration cfg = new Configuration (). configure (); sessionfact Ory = cfg. buildSessionFactory ();} public static Session getSession () {return sessionfactory. openSession () ;}// add public static void add (Object obj) {Session session = null; Transaction tx = null; try {session = HibernateUtils. getSession (); tx = session. beginTransaction (); session. save (obj); // difference: If the save () method does not enable transactions, it will execute an insert statement. However, since no transaction is committed, it will execute another // session. persist (obj); // rolled back, while the persist () method does not execute when the transaction is not started, that is, there is no such insert Statement tx. commit ();} finally {if (session! = Null) {session. close () ;}}// modify public static void update (Object obj) {Session session = null; Transaction tx = null; try {session = HibernateUtils. getSession (); tx = session. beginTransaction (); session. update (obj); tx. commit ();} finally {if (session! = Null) {session. close () ;}}// delete public static void delete (Object obj) {Session session = null; Transaction tx = null; try {session = HibernateUtils. getSession (); tx = session. beginTransaction (); session. delete (obj); tx. commit ();} finally {if (session! = Null) {session. close () ;}}// you do not need to enable the public static Object findById (Class clazz, Serializable id) {Session session = null; try {session = HibernateUtils. getSession (); // The difference between get () and load () needs to be distinguished here, load () do not access the database immediately. // The database will be loaded only when it is used for the first time. // The load method will never return an empty object (if it does not exist, it will generate a sub-class of the user. For details, you can check the data and distinguish the two methods. // Object obj = session. load (clazz, id); Object obj = session. get (clazz, id); return obj;} finally {if (session! = Null) {session. close ();}}}}


Finally, the addition, deletion, modification, and query operations of an object are completed. We can rewrite the Main. java file to use the HibernateUtils tool class to operate the object:

Main. java

Package toone.com.cn; import java. util. date; import toone.com.cn. bo. user; import toone.com.cn. util. hibernateUtils; public class Main {public static void main (String [] args) {User user = new User (); user. setName ("Kobi"); user. setBirthday (new Date (); HibernateUtils. add (user); // add user. setName ("Jams"); HibernateUtils. update (user); // modify HibernateUtils. delete (user); // delete User user1 = (User) HibernateUtils. findById (User. class, user. getId (); // find the System. out. println (user1.getName ());}}



Conclusion: I learned the basic functions of Hibernate and learned how to use it for addition, deletion, modification, and query operations. It is a little bit of work, so I have to keep posting and learning!



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.