Hibernate brief and getting started instance, hibernate brief instance

Source: Internet
Author: User

Hibernate brief and getting started instance, hibernate brief instance
I. Hibernate

 

In summary, Hibernate is a lightweight persistence layer framework of ORM, which solves the problem of table mismatch (impedance mismatch) between objects and relational databases) it also has the advantage (non-invasive) that the development code does not need to inherit from the hibernate class or interface ). The implementation of the hibernate framework allows developers to avoid repeated compilation of Java/jdbc code and apply Object-oriented Thinking to relational databases.

II. use myeclipse to create a hibernate instance (taking hibernate3.5.2 and mysql as an example. cfg. xml and *. hbm. xml file 1. create a java project, import all jar packages in the lib \ required folder, mysql jar packages, and hibernate3.jar packages to the lib folder created in the java project, right-click all the jar files and choose Build Path> Add Build Path. In the src folder, create a pro package, test package, and hibernate. cfg. xml file
2. Create the Student object class under the pro package (PS: myeclipse automatically generates the get/set Method: Ctrl + Shift + s-> Generate Getters and Setters)
 1 package test.hibernate.pro;   2    3 public class Student {   4     int id;   5     int age;   6     String name;   7     int classid;   8     public int getId() {   9         return id;  10     }  11     public void setId(int id) {  12         this.id = id;  13     }  14     public int getAge() {  15         return age;  16     }  17     public void setAge(int age) {  18         this.age = age;  19     }  20     public String getName() {  21         return name;  22     }  23     public void setName(String name) {  24         this.name = name;  25     }  26     public int getClassid() {  27         return classid;  28     }  29     public void setClassid(int classid) {  30         this.classid = classid;  31     }  32 }  

3. Create a table using MysqlGUI or the cmd window (you can also use the SchemaExport method of hibernate to automatically generate the table structure ). In the cmd window, Enter mysql-hlocalhost-u root-p in the lib directory of the mysql folder, and Enter Password to Enter create a table in the database.

4. Create the *. hbm. xml file under the pro package to import the header file, and map the object to the table structure.

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <! DOCTYPE hibernate-mapping PUBLIC 3 "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 5 

5. Configure the hibernate. cfg. xml file

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <! DOCTYPE hibernate-configuration PUBLIC 3 "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" 4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 5 6 

6. Run test. java test under the test package.

1 package test. hibernate. test; 2 3 import org. hibernate. session; 4 import org. hibernate. sessionFactory; 5 import org. hibernate. transaction; 6 import org. hibernate. cfg. configuration; 7 8 import test. hibernate. pro. student; 9 10 public class test {11 public static void main (String [] args) {12 Configuration cfg = new Configuration (). configure (); 13 14 // Write statement 15 SessionFactory sf = cfg. buil DSessionFactory (); 16 // hibernate4.0-hibernate4.2 write Method 17 // ServiceRegistry reg = new 18 // ServiceRegistryBuilder (). applySettings (cfg. getProperties () 19 //. buildServiceRegistry (); 20 // Writing Method 21 // ServiceRegistry reg = new 22 // StandardServiceRegistryBuilder (). applySettings (cfg. getProperties () 23 //. build (); 24 // SessionFactory sf = cfg. buildSessionFactory (reg); 25 26 Session se Ssion = null; 27 Transaction ta = null; 28 try {29 session = sf. openSession (); 30 ta = session. beginTransaction (); 31 32 Student stu = new Student (); 33 stu. setAge (17); 34 stu. setName ("Neo"); 35 stu. setClassid (2); 36 session. save (stu); 37 38 ta. commit (); 39} catch (Exception e) {40 e. printStackTrace (); 41 if (ta! = Null) {42 ta. rollback (); 43} 44} finally {45 if (session! = Null & session. isOpen () {46 session. close (); 47} 48} 49} 50}
B) Use myeclipse to automatically generate the hibernate. cfg. xml and *. hbm. xml files

1. Create a java web project and create the pro, factory, dao, and test packages under the src directory.

2. Open the taskbar window-> Show View-> DB Browser and import the mysqljar package to create a mysql jdbc Driver. Right-click the project-> MyEclipse-> ProjectFacets-> Install Hibernate Facet to create the hibernate. cfg. xml and SessionFactory files and name them SF. java.


3. In DB Browser, right-click the table structure Hibernate Reverse Engineering to generate the entity class to the pro package in Reverse direction. Select three check points, select the primary key growth policy, and select native (default: native) in the instance)

4. Create a dao layer class in the dao package

 1 package test.hibernate.dao;   2    3 import org.hibernate.Session;   4 import org.hibernate.Transaction;   5    6 import test.hibernate.factory.SF;   7 import test.hibernate.pro.Student;   8    9 public class StudentDao {  10     Session session = null;  11     Transaction ta = null;  12   13     public void addStudent(Student stu) {  14         try {  15             session = SF.getSession();  16             ta = session.beginTransaction();  17             session.save(stu);  18             ta.commit();  19         } catch (Exception e) {  20             e.printStackTrace();  21             if (ta != null)  22                 ta.rollback();  23         } finally {  24             if (session != null)  25                 session.close();  26         }  27     }  28 }  

5. Create a test in the test package

 1 package test.hibernate.test;   2    3 import test.hibernate.dao.StudentDao;   4 import test.hibernate.pro.Student;   5    6 public class Test {   7     public static void main(String[] args) {   8         StudentDao sd = new StudentDao();   9           10         Student stu = new Student();  11         stu.setStuAge(19);  12         stu.setStuName("Mike");  13         stu.setStuClassid(1);  14           15         sd.addStudent(stu);  16     }  17 }  
In summary, hibernate implements orm object relationship ing, and adds, deletes, modifies, and queries database data in the form of objects, thus improving programming efficiency.

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.