Write the first Hibernate program manually

Source: Internet
Author: User

Hibernate is a popular Object/Relation Mapping (ORM) framework and has been widely used in enterprise-level application development. So what is ORM?
 

This is the case in the IT world. I always like to make some seemingly uncertain terms, and make us confused, what ORM, cloud computing, and so on. IT seems that only in this way can we show the elegance of IT. However, this can be disastrous for beginners. They may say in their hearts: Will this stuff be difficult? Can I learn it? In short, it has a negative impact on the self-confidence of beginners.
 

We can borrow a classic saying from Grandpa Mao: strategically despise it and tactically attach importance to it. That is to say, we must first establish confidence, believe that it is not an uncertain thing, and we can fully learn it. To achieve this goal, we will attach importance to it tactically and study it carefully to achieve our strategic goal.
Any technology exists to solve a problem, not to exist. ORM is nothing more than: our current mainstream programming languages are object-oriented, and we all like to operate on objects. For example, a user Object must have its own ID, the attributes such as name, age, and gender are operated on by the user object. However, this user object must be saved to the database (the so-called persistence) for later use. Currently, mainstream databases are relational databases, the user object ID and other attributes are the columns of a row in a table in the database. If we use traditional JDBC to access these attributes, not only is it cumbersome (kids who have written JDBC code will understand it), but it is not intuitive (we have to imagine that the value of a column is an attribute of an object, that is, we operate on columns rather than objects), and we have to write a lot of JDBC code repeatedly. The consequence is that the development efficiency is low and the error probability is high; to solve this problem, Hibernate was born. With the help of it, we only need to operate the object attributes at the object level (is it very consistent with humans? ?), Then Hibernate will automatically help us to feed back our operations on the object to one or more fields in the corresponding row of the corresponding table in the database (the JDBC code and SQL statement here will help us automatically Generated ). In this way, do we save a lot of trouble? The development efficiency and quality will be improved accordingly.
Now, are you eager to try these powerful functions of Hibernate? This is also true when I started learning Hibernate. But what I have seen is that when I introduce how to write the first Hibernate program, I don't need to use Maven, I need to use ant, and so on! Does this increase the difficulty of my learning? Fortunately, it was a long way to go through the dark moment. To help beginners do not take a detour, you can write your first Hibernate program as soon as possible to improve self-confidence and strategically despise it, the following describes how to write your first Hibernate Program (Hibernate 3.6.7 Final: http://sourceforge.net/projects/hibernate/files/hibernate3/3.6.7.Final ).
Here, I would like to explain three goals of manual writing: First, you do not need to be familiar with the usage of eclipse and other IDE or ant tools; second, let you understand the program running mechanism, you can understand how the program runs. The third is to let you know what IDE has done for you.
Now, let's talk less and start with the question. To write this program, I chose SQL Server 2008 as our database Server because it is relatively easy to use compared with other DBMS. In one sentence, reduce the difficulty and write our first program as soon as possible. Here we simulate user management, assuming that each user has its own ID, name, age, and Gender attributes. We first create the database mydb in SQL Server, and then create the table users, including the following fields: ID (identity (), that is, the auto-increment field, starting from 1, 1), name (nvarchar (10), age (int), and gender (nvarchar (1 )). Next, we use Hibernate to write a program and add a user information to the table. To write this program, I created a FirstHibernate directory under directory E: \ DemoPrograms to store all the files involved in this program.
The first step is to write a class that represents the User entity. Here we write a User class (User. java ). Corresponds to the users table fields in the database (ing, mapping). We define attributes such as ID for the User class and the setter and getter methods for these attributes, this facilitates operations on these attributes of user entities. The Code is as follows (if the class is declared as the package when it is defined, the class file generated after the compilation is easy to error, so all the classes in this Article do not have the package declaration ):

Public class User {private int id; private String name; private int age; private String gender; 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 int getAge () {return age;} public void setAge (int age) {this. age = age;} public String getGender () {return gender;} p Ublic void setGender (String gender) {this. gender = gender;} after writing the code, save the User. java file to the FirstHibernate directory.
Step 2: In order to let Hibernate know which field of the users table corresponds to the attributes of the User object (that is, the attributes defined in the User class), we need to provide a ing file. To this end, we create a file named User. hbm. xml (the file name consists of the class name User, and the common suffix hbm. xml. Hbm should be hibernate ing !), Placed in the FirstHibernate directory. This is a typical XML file with the following content:

<? Xml version = "1.0" encoding = "gb2312"?> <! -- Encoding = "gbk" in the preceding line specifies the encoding type of this file. This line of information must appear in the first line of the file, even if there are blank lines or comments. Otherwise, an error is reported. --> <! -- Specify the relevant DTD information and routine information, just copy it. --> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate Mapping DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <! -- Specify the ing relationship in the hibernate-mapping element --> Step 3, we should also tell hibernate where to connect to the database, the username and password used, and the JDBC driver. This requires a configuration file to save this information. Here we use a large number of xml files (the other is the properties attribute file that is rarely used ), the default file name is hibernate. cfg. xml, the content is as follows.

<? Xml version = "1.0" encoding = "gb2312"?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <! -- Hibernate-configuration is the root element of the configuration file. configuration information is contained in this element. --> <Hibernate-configuration> <! -- Session-factory sub-element. --> <Session-factory> <! -- Specify the driver class to connect to SQL Server 2008. You need to provide relevant JAR packages, which can be downloaded from the official Microsoft website. --> <Property name = "connection. driver_class"> com. microsoft. sqlserver. jdbc. SQLServerDriver </property> <! -- Connection URL --> <property name = "connection. url"> jdbc: sqlserver: // localhost; databaseName = mydb </property> <! -- Username and password --> <property name = "connection. username"> sa </property> <property name = "connection. password"> admin123 </property> <! -- Use a built-in connection pool with a size of 1 --> <property name = "connection. pool_size"> 1 </property> <! -- Because of the differences between different databases, hibernate needs the relevant database dialect to handle such differences. The database dialect for SQL Server is specified as follows. --> <Property name = "dialect"> org. hibernate. dialect. SQLServerDialect </property> <property name = "current_session_context_class"> thread </property> <property name = "cache. provider_class "> org. hibernate. cache. noCacheProvider </property> <! -- Output the SQL statement generated by hibernate to the standard output device. --> <Property name = "show_ SQL"> true </property> <! -- Specify the ing file to be used, which we just created. --> <Mapping resource = "User. hbm. xml"/> </session-factory> What should we do next? So far, we have written JAVA programs and configuration files. Why didn't we see any shadows of the hibernate framework? Yes, The hibernate framework is a JAR package provided to us, and we haven't seen it yet. These JAR packages can be freely downloaded from the official hibernate website. The JAR packages used in this example (some of which are third-party JAR packages) are as follows:
 


Here, hibernate3.jar is the core package, and the interface to be used right away is like org. hibernate. session and org. hibernate. sessionFactory and org. hibernate. cfg. configuration, and their definitions are in this package. The last JAR package, that is, sqljdbc4.jar, is a JDBC driver provided by Microsoft to access SQL Server. In the configuration file hibernate. cfg. the driver class specified in xml is in this JAR package. Hibernate will use this driver to operate our database. What are the specific functions of other JAR packages? I will not detail them here. As we use hibernate more and more, I believe that we will gradually understand and become familiar with it. Create a lib directory under the FirstHibernate directory to save these JAR packages.
In the last step, we write a JAVA class with the main method to drive hibernate to access the database for us. The program name is TestHibernate. java, which is placed in the FirstHibernate directory. Its content is as follows:

// Introduce hibernate related interfaces and classes from the JAR package. Import org. hibernate. session; import org. hibernate. sessionFactory; import org. hibernate. cfg. configuration; import java. util. random; public class TestHibernate {public static void main (String [] args) {// create a Configuration object, which represents the hibernate Configuration of our program to the database. Call its configure () method to automatically search for the hibernate. cfg. xml configuration file. Configuration cfg = new Configuration (). configure (); // call the buildSessionFactory () method of the Configuration object to // create a session factory object. SessionFactory factory = cfg. buildSessionFactory (); // obtains the Session (Session) object session Session = factory from the Session factory. getCurrentSession (); // start the transaction session. beginTransaction (); User user = new User (); user. setName (""); user. setAge (new Random (). nextInt (21) + 20); user. setGender ("male"); // Save the user to the users table in the database. Here, hibernate will use the information in the // User ing file User. hbm. xml. Is it easier to directly Save the user object than to save the name, age, and other information separately? // Hibernate will automatically generate an insert statement for us. Session. save (user); // submit the transaction. Session. getTransaction (). commit (); // close SessionFactory factory. close () ;}} so far, it seems that this is a success. Let's compile and run this program to see what effect it has. As a preparation, first make sure that you have set the classpath environment variable and add the current directory (.) to this variable. In the command line window, you can temporarily set only the classpath environment variables that are valid for this command window and add the current directory. The command is set classpath = .. The following describes the settings. Open the command line window, switch to the E: \ DemoPrograms \ FirstHibernate directory, run the javac * java command to compile all JAVA source programs.
After a long and anxious wait, we encounter several errors. Take a closer look, the core error is that the org. hibernate and org. hibernate. cfg software packages cannot be found. Of course not found! The class files of these two packages are in the hibernate3.jar package, but we didn't add this jar package to the classpath, so of course we won't be able to find it. How to add it? Because the JAR package is in the directory E: \ DemoPrograms \ FirstHibernate \ lib, we can write the following command:
Set classpath = % classpath %; E: \ DemoPrograms \ FirstHibernate \ lib \ hibernate3.jar.
Here, % classpath % refers to extracting the existing values of classpath and adding the values we need to add. They must be separated by semicolons, the new classpath is obtained. Note: The hibernate3.jar file must be available. Instead of packaging the class file, you do not need to provide the JAR package name JAVA to find the corresponding class file. The JAR package is also similar to a directory. If you make such a mistake, it is very difficult to make a mistake.
After running this command, we can compile it again, so there is no problem.
After the compilation is successful, the next step is to run. Since the compilation is successful, isn't it a logical task to run successfully? Before running SQL Server, make sure that the SQL Server service is enabled. Otherwise, how can I access the database? In the command window, enter the following command to run our program: java TestHibernate.
When you are excited to wait for the correct execution of your first hibernate program, the program reports an error message: java. lang. NoClassDefFoundError.
Is it like a splash of cold water? Don't be discouraged. Learning Program Design often encounters such a problem. The error is not terrible. If we analyze the error information carefully, we can find the cause of the error. This error message means that it cannot find the definition of the org. dom4j. enentexception class. We didn't use this class in the program, so we can naturally guess that Hibernate used this class. This class is in the JAR package dom4j-1.6.1.jar, and we have put this JAR package under the lib directory. What we need to do now is to run a set command similar to the previous one and add the JAR package to the classpath environment variable so that JAVA can find the org. dom4j. enentexception class definition.
In fact, each JAR package placed in the lib directory must be used. The above method solves the issue of org. dom4j. DocumentException class, but there will still be a lot of Hibernate to use, or the classes to be used by other modules called by Hibernate cannot be found. These classes are included in the remaining JAR packages. You can try it yourself. If you run the program now, it will also report that the XX class cannot be found, and we have to add the JAR package of this class to the classpath environment variable. Then, an error is reported indicating that the YY class cannot be found until we add all the JAR packages. To add these JAR packages to classpath at one time, I wrote a batch processing file setclasspath. bat, which is placed in the FirstHibernate directory. If the Directory and directory structure you have created, as well as the storage location of each file, are exactly the same as the author (including the disk, I am an edisk here ), you can use this batch file directly. The source code is as follows (use the UltraEdit or Windows notepad text editor to create a text file and change its suffix to bat to create a batch file. Open it in a text editor and enter the doscommand you want to execute ).
Set classpath = .; e: \ DemoPrograms \ FirstHibernate \ lib \ hibernate3.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ sqljdbc4.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ dom4j-1.6.1.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ slf4j-api-1.6.2.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ slf4j-simple-1.6.2.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ hibernate-jpa-2.0-api-1.0.1.Final.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ cglib-2.2.jar; E : \ DemoPrograms \ FirstHibernate \ lib \ commons-collections-3.1.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ javassist-3.12.0.GA.jar; E: \ DemoPrograms \ FirstHibernate \ lib \ jta-1.1.jar now run the program again.
Author: Xiao fan

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.