Eclipse integrated Hibernate operations SQL Server Instance

Source: Internet
Author: User
Tags generator jboss

Eclipse builds the Hibernate development environment, using a database of Sqlserver2008

1, need to successfully install Eclipse, if not installed can be online to check information.

2, after the Eclipse installation is successful, click Help--> Eclipse Marketplace, search JBoss Tools, select Hibernate components, click Install, select the JBoss plugin to install, all the way to the default, Restart Eclipse When you are finished installing.

  

3, after the successful installation, New-->other, enter H, you can see the hibernate components, instructions to install Hibernate plugin success.

  

4, the first Hibernate project, just start learning just new Java project can be. After the project is built, we need to import Hibernate jar package (for insurance, all import, I use the Hibernate4), can download here: Https://pan.baidu.com/s/1iIwykYn5WngEUvF1MqmSoA, Password: Plus: z1639701126, which includes all the jar packages and source code required for the project (original is not easy, need to encourage ha)

  

5, if there are classmates do not know how to guide the package, it's okay, I'll teach you, right-click Project-->build path-->configure Build path-->libraries-->add extenal jars, Find the package you just downloaded, add it all in, (don't forget the JDBC, I chose SQLJDBC4).

6. Now the required environment in the project has been set up, then the code-level operation. Enter the project to create a new persistence layer for the package and class, and here I am news.java for example.

Importjava.util.Date; Public classNews {PrivateInteger ID; PrivateString title; PrivateString content; PrivateDate date;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString GetTitle () {returntitle; }     Public voidSettitle (String title) { This. title =title; }     PublicString getcontent () {returncontent; }     Public voidsetcontent (String content) { This. Content =content; }     PublicDate getDate () {returndate; }     Public voidsetDate (date date) { This. Date =date; }     PublicNews (string title, string content, date date) {Super();  This. title =title;  This. Content =content;  This. Date =date; }     PublicNews () {//TODO auto-generated Constructor stub    }}
View Code

It is important to note that:

    • To provide a parameterless constructor. So that hibernate can use Constructor.newinstance () to instantiate a persisted class.
    • Provides an identity property. Typically maps to a primary key field of a database table. Without this attribute, some features will not work, such as: Session.saveorupdate ().
    • Declares an access method (Get/set) for a field of a persisted class. Hibernate persists the attributes of the JavaBeans style.
    • Use a non-final class. Generating agents at run time is an important feature of Hibernate. If the persisted class does not implement any interfaces, Hibnernate uses the CGLIB build agent. If you are using the final class, you cannot generate the Cglib proxy.
    • Override the Eqauls () and Hashcode () methods. If you need to put an instance of a persisted class into the set (when you need to do the correlation mapping), you should override both methods.

7. Create object-relational mapping file:

  Right-click the package name of the Persistence class, New---Hibernate XML Mapping file (hbm.xml), select News class, Finish, The object-relational mapping file for the new class will be generated News.hbm.xml, setting the class property of <generator> below <id> to "native", which specifies that the primary key is generated in a local way using the database: 

<?XML version= "1.0"?><!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--Generated 2018-7-18 10:45:25 by Hibernate Tools 3.5.0.Final -<hibernate-mapping>    <classname= "News"Table= "News">        <IDname= "id"type= "Java.lang.Integer">            <columnname= "ID" />            <Generatorclass= "Native" />        </ID>        < Propertyname= "title"type= "Java.lang.String">            <columnname= "TITLE" />        </ Property>        < Propertyname= "Content"type= "Java.lang.String">            <columnname= "CONTENT" />        </ Property>        < Propertyname= "Date"type= "Java.util.Date">            <columnname= "DATE" />        </ Property>    </class></hibernate-mapping>

8. Create Hibernate configuration file:
Right-click New------Hibernate configuration file---Next, using the default name Hibernate.cfg.xml, clicking Finish and then configuring the database connection related information in the file:

  

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hi Bernate.org/dtd/hibernate-configuration-3.0.dtd "><hibernate-configuration>    <session-factory>     <!--Configure basic information for a connected database -        < Propertyname= "Connection.username"> User name</ Property>        < Propertyname= "Connection.password"> Your password</ Property>        < Propertyname= "Connection.driver_class">Com.microsoft.sqlserver.jdbc.SQLServerDriver</ Property>        < Propertyname= "Connection.url">jdbc:sqlserver://your computer ip:1433;database= the database name</ Property>        <!--Configure basic information for Hibernate -        <!--database dialect used by hibernate -        < Propertyname= "dialect">Org.hibernate.dialect.SQLServerDialect</ Property>               <!--whether to print SQL in the console when you perform an action -        < Propertyname= "Show_sql">True</ Property>        <!--whether to format SQL -        < Propertyname= "Format_sql">True</ Property>        <!--specify policies that automatically generate data tables -        < Propertyname= "Hbm2ddl.auto">Update</ Property>        <!--specifies the associated. hbm.xml file, if it is written in the package, such as: Com/entity/address.hbm.xml -        <MappingResource= "News.hbm.xml"/>        </session-factory></hibernate-configuration>

9. Test:
Create a new test class, Test save a new object to the database with the following code, and then look for the record and output it.

  

Importjava.util.Date;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.Transaction;Importorg.hibernate.cfg.Configuration;ImportOrg.hibernate.service.ServiceRegistry;ImportOrg.hibernate.service.ServiceRegistryBuilder; Public classTest { Public Static voidTest () {//Create a Sessionfactory objectSessionfactory sessionfactory =NULL; //to create a Configuration object: Basic configuration information and object-relational mapping information corresponding to hibernateConfiguration Configuration =NewConfiguration (). Configure (); //Create a Serviceregistry object: Hibernate 4.x newly added object//any configuration and service of hibernate needs to be registered in the object before it can be valid.Serviceregistry Serviceregistry =NewServiceregistrybuilder (). Applysettings (Configuration.getproperties ())        . Buildserviceregistry (); Sessionfactory=configuration.buildsessionfactory (serviceregistry); //Create a Session objectSession session =sessionfactory.opensession (); //Open TransactionTransaction Transaction =session.begintransaction (); //perform save and load operationsNews news =NewNews ("Java", "Zhangsan",NewDate (Newjava.util.Date (). GetTime ());        Session.save (news); //load a news record with ID 1 in the databaseNews news1 = (news) Session.get (news).class, 1);        SYSTEM.OUT.PRINTLN (news); //5. Commit a transactionTransaction.commit (); //6. Close SessionSession.close (); //7. Close the Sessionfactory objectSessionfactory.close (); }     Public Static voidMain (string[] args) {test (); }    }

10, directly execute the code, the execution of the SQL statement will be printed in the console, as follows:

  

11. New News table and inserted data will be created in the database.

  

Eclipse integrated Hibernate operations SQL Server Instance

Related Article

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.