Hibernate Beginner---annotation configuration

Source: Internet
Author: User

SSH framework is the basic skills of each Java programmer, although the work is not used, or to learn, do some study notes, is a little accumulation of it.

Needless to say, start with a simple demo, feel a little.

Development tools: MyEclipse 10

Database: MySQL

Create a simple Java project,

The first step is to create a student class with the following code:

 PackageCom.huawei.vo;Importjavax.persistence.Entity;ImportJavax.persistence.GeneratedValue;ImportJavax.persistence.GenerationType;Importjavax.persistence.Id; @Entity Public classStudents {Private intSID; PrivateString sname; @Id//Set Primary Key@GeneratedValue (strategy = Generationtype.auto)//PRIMARY Key auto-grow policy     Public intGetSID () {returnSID; }     Public voidSetsid (intSID) {         This. Sid =SID; }     PublicString Getsname () {returnsname; }     Public voidsetsname (String sname) { This. sname =sname; }        }

Hibernate's ORM technology is famous for mapping Java objects directly to tables, and Hibernate provides two ways to describe the mapping of objects to tables.

The first is to create a mapping to describe the configuration file, the name is also very normative, to play a Students.hbm.xml, this way I do not like, and I want to be a lot of domain objects,

It's not about a bunch of mapping files, it's a decision to give up.

The second is an annotation-based approach, and it looks like the code is elegant, as in the code above. This means that the object-to-table mappings are already included in the domain object student.

The second step is to create a new hibernate configuration file Hibernate.cfg.xml in the SRC directory, configured as follows:

<?XML version= ' 1.0 ' encoding= ' UTF-8 '?><!DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hi Bernate.sourceforge.net/hibernate-configuration-3.0.dtd "><!--Generated by MyEclipse Hibernate Tools.  -<hibernate-configuration><session-factoryname= "MySQL">    < Propertyname= "Connection.driver_class">Com.mysql.jdbc.Driver</ Property>    < Propertyname= "Connection.url">jdbc:mysql://localhost:3306/hibernate</ Property>    < Propertyname= "Connection.username">Root</ Property>    < Propertyname= "Connection.password">Root</ Property>    < Propertyname= "dialect">Org.hibernate.dialect.MySQL5Dialect</ Property>    <!--Background Printing sql for easy debugging -    < Propertyname= "Show_sql">True</ Property>    < Propertyname= "Hbm2ddl.auto">Update</ Property>    < Propertyname= "Current_session_context_class">Thread</ Property>    <Mappingclass= "Com.huawei.vo.Students" /></session-factory></hibernate-configuration>

Be sure to load the class of the mapping relationship through the <mapping> tag in sessionfactory. This is even configured.

When using Getcurrentsession () to get the session, be sure to set the Current_session_context_class property to Thread

The third step, write a unit test class bar, the code is as follows:

 PackageCom.huawei.vo;Importjunit.framework.TestCase;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.Transaction;Importorg.hibernate.cfg.AnnotationConfiguration; Public classTeststudentsextendstestcase{Private Staticsessionfactory sessionfactory; @Overrideprotected voidSetUp ()throwsException {sessionfactory=Newannotationconfiguration (). Configure (). Buildsessionfactory (); } @Overrideprotected voidTearDown ()throwsException {sessionfactory.close (); }     Public voidTestsave () {Session session=sessionfactory.getcurrentsession (); Transaction TX=session.begintransaction (); Try{Students s=NewStudents (); S.setsname ("Yaoying");            Session.save (s);        Tx.commit (); }        Catch(Exception ex) {tx.rollback (); }    }}

There are two ways to get a session here:

1, through the Sessionfactory opensession () to obtain.

2, through the Sessionfactory getcurrentsession () to obtain.

Because the second method gets a session that is bound to the current thread, that is, each time a single-threaded operation obtains the same session, and hibernate after the commit and rollback of the transaction

Automatically help you to complete the session closed operation, if it is opensession each time will get a new session instance, need to manually complete the session closed.

Finally, you will see a green progress bar after performing testsave success.

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.