Hibernate_HelloWord, phphelloword

Source: Internet
Author: User

Hibernate_HelloWord, phphelloword

Hibernate operation steps

1. create a project 2. add jar package 3. write the XML configuration file hibernate. cfg. xml4. write log4j. properties Log File 5. create a student table in the MySql database. create a Student object class (create a table first and then a class) 7. write the XML ing file Student. hbm. xml, or Annotation ing Statement 8. in hibernate. cfg. add the corresponding mapping9. write Test class main or Junit Test class to xml (right-click the project --> "New" --> "Junit Test Case ")

HelloWorld applet-XML ing File

1. Create a project

2. Add the jar package. The jar packages listed here are all jar packages required by Hibernate. Not all jar packages are required in this project.

Encapsulate the following jar package into a User Library named hibernateantlr-2.7.6.jarc3p0-0.9.1.jarcommons-collections-3.1.jardom4j-1.6.1.jarhibernate3.jarhibernate-annotations.jarhibernate-commons-annotations.jarhibernate-jpa-2.0-api-1.0.0.Final.jarjavassist-3.12.0.GA.jarjta-1.1.jarjunit-4.10.jarlog4j-1.2.14.jarmysql-connector-java-5.1.7-bin.jarslf4j-api-1.6.1.jarslf4j-log4j12-1.6.1.jar

3. hibernate. cfg. xml configuration file. <Mapping/> in Step 8, Set

<? Xml version = '1. 0' encoding = 'utf-8'?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 

4. log4j. properties Log File

### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file hibernate.log ####log4j.appender.file=org.apache.log4j.FileAppender#log4j.appender.file.File=hibernate.log#log4j.appender.file.layout=org.apache.log4j.PatternLayout#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=warn, stdout#log4j.logger.org.hibernate=info#log4j.logger.org.hibernate=debug### log HQL query parser activity#log4j.logger.org.hibernate.hql.ast.AST=debug### log just the SQL#log4j.logger.org.hibernate.SQL=debug### log JDBC bind parameters ####log4j.logger.org.hibernate.type=info#log4j.logger.org.hibernate.type=debug### log schema export/update ####log4j.logger.org.hibernate.tool.hbm2ddl=debug### log HQL parse trees#log4j.logger.org.hibernate.hql=debug### log cache activity ####log4j.logger.org.hibernate.cache=debug### log transaction activity#log4j.logger.org.hibernate.transaction=debug### log JDBC resource acquisition#log4j.logger.org.hibernate.jdbc=debug### enable the following line if you want to track down connection ###### leakages when using DriverManagerConnectionProvider ####log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

5. Create a table in the database

You can create a table manually in the database or automatically by running the program.

Automatic table creation here

6. Create a Student object class

public class Student {private int id;private String name;private int age;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;}}

7. Student. hbm. xml ing File

<? Xml version = "1.0"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

8. Add the corresponding ing in hibernate. cfg. xml.

9. Write test class main

public class StudentTest {public static void main(String[] args) {Student s = new Student();s.setName("s3");s.setAge(10);SessionFactory sf = new Configuration().configure().buildSessionFactory();Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();sf.close();}}

After running the program, the student table is automatically created in the database and the object s is saved to the student table.

HelloWorld applet ---- Annotation ing statement

Steps 1-5 are the same as above

6, 7. Create an object class and add an Annotation

@ Entity // indicates that this is an Entity class, which corresponds to a table in the database in the public class Teacher {private int id; private String name; private int age; @ Id // primary key @ GeneratedValue // ID generation policy. The default value is AUTOpublic 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 ;}}

8. Add the corresponding ing in hibernate. cfg. xml, as shown below:

<mapping class="com.hibernate.model.Student"/>

9. Write test class

There are many ways to test the class

A) See the main test class above.

B) Create a HibernateUtil auxiliary class, and then create the test class main

public class HibernateUtil {private static SessionFactory sf = buildSessionFactory();private static SessionFactory buildSessionFactory() {return new Configuration().configure().buildSessionFactory();}public static SessionFactory getSessionFactory() {return sf;}}

 

public class StudentTest {public static void main(String[] args) {Student s = new Student();s.setName("lisi");s.setAge(18);SessionFactory sf = HibernateUtil.getSessionFactory();Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();sf.close();}}

C) Create a Junit test class

Right-click the project --> "New" --> "Junit Test Case", enter the class name, and then complete the test method.

public class StudentTest_Junit {private static SessionFactory sf = null;@BeforeClasspublic static void beforeClass(){sf = new Configuration().configure().buildSessionFactory();}@AfterClasspublic static void afterClass(){sf.close();}@Testpublic void test() {Student s = new Student();s.setName("wangwu");s.setAge(23);Session session = sf.getCurrentSession();session.beginTransaction();session.save(s);session.getTransaction().commit();}}

After running the program, the student table is automatically created in the database and the object s is saved to the student table.


How to Use hibernate

I can only tell you how to use hibernate in MyEclipse.
For automatic generation, you must first establish a connection with the database under Myeclipse:
1) window-show view-other-DB browser
Right-click in the blank area and click new,
In the second row of the dialog box, you can enter your own name, which does not affect the program. Therefore, you can enter the database name, such as MySql, and then enter the user name and password. Click test driver to test the connection.
Note that the third line should be changed to jdbc: microsoft: sqlserver: // your server name: 1433. If it is another one, change it accordingly.
Then add jars to add the driver. If the data source is connected, you must configure the data source. This is not configured in IDE, so it is not detailed.
In this way, you can operate the database directly in the IDE. The efficiency will be much faster.

2) Add reverse engineering. Double-click the database connection you just created, connect to it, find your database, find the table you want to add, right-click Hibernate reverse engineering, and create one in sequence according to the wizard.

Hibernate has several mappings.

There are several types of Hibernate ing relationships:

1. Unidirectional N-1

2. Unidirectional 1-1

3. Unidirectional 1-N

4. Unidirectional N-N

5. Bidirectional 1-N

6. Bidirectional N-N

7. Bidirectional 1-1

The following is a simple summary of the seven associations:

I. One-way multi-to-one

View two POJO

Public class Person {

Private int pid;

Private String name;

Private Address address;

... // Generate the corresponding getter and setter Methods

}

----------------------------------------

Public class Address {

Private int id;

Private String detail;

... // Generate the corresponding getter and setter Methods

}

Here we need to maintain the relationship is that multiple persons can correspond to the same address, using a one-way N-1 ing we only need to add a foreign key at one end to one end.

** View the configuration file

<Class name = "Person">

<Id name = "id">

<Generator class = "native"/>

</Id>

... // Some field configurations are omitted

<Your-to-one name = "address" column = "addressId"/> // key Configuration

</Class>

After this configuration, hibernate will add a foreign key SSID to point to one end at one end (Person ).

2. Unidirectional 1-1 (foreign key Association)

You can use the <sequence-to-one> label to specify unique = true for multiple ends. This limits the uniqueness of multiple ends.

Ing one-to-one unique foreign key association using this method

You only need to modify the configuration file:

<Your-to-one name = "address" column = "addressId" unique = "true"/>

3. Unidirectional 1-N

** Looking at the code, we know that a class has multiple students. This is a typical 1-N relationship.

Public class Classes {
Private int id;
Private String name;
Private Set students;

... // Generate the corresponding getter and setter Methods

}

---------------------------------------------------------------------------

Public class Student {
Private int id;
Private String name;

.. // Generate the getter and setter methods.

}

** Ing principle: One-to-Multiple Association ing adds a foreign key to one end on multiple ends, and maintains a link pointing to multiple

** Configuration file:

<Class name = "Classes" table = "t_classes">
<Id ...... remaining full text>

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.