hibernate--Simple increase, delete, change, check operation

Source: Internet
Author: User

Ideas:

1. Import Hibernate jar Package

2. Import the MySQL jar package

3. Create a Database

4. Creating Java Entity classes

5. Writing the Hibernate.cfg.xml configuration file

6. Writing DAO classes

Directory:

Data sheet:

Entity class:

 PackageOnline.shixun.model;Importjava.util.Date;ImportJavax.persistence.Column;Importjavax.persistence.Entity;ImportJavax.persistence.GeneratedValue;ImportJavax.persistence.GenerationType;Importjavax.persistence.Id;Importjavax.persistence.Table;/*** Entity class *@authorTom **/@Entity @table (name= "Commodity") Public classCommodity {@Id @GeneratedValue (strategy= generationtype.identity)//primary key self-increment    PrivateInteger ID; @Column (Name= "CreateDate")    PrivateDate CreateDate;//Date Created@Column (Name= "described")    PrivateString describe;//Product Description@Column (Name= "Modifydate")    PrivateDate modifydate;//Date Modified@Column (Name= "Name")    PrivateString name;//Product Name//constructor Function     Publiccommodity () {}//with parameter constructors     PublicCommodity (Date createdate,string describe,date modifydate,string name) { This. CreateDate =CreateDate;  This. describe =describe;  This. modifydate =modifydate;  This. Name =name; }     PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicDate getcreatedate () {returnCreateDate; }     Public voidsetcreatedate (Date createdate) { This. CreateDate =CreateDate; }     PublicString Getdescribe () {returndescribe; }     Public voidSetdescribe (String describe) { This. describe =describe; }     PublicDate getmodifydate () {returnmodifydate; }     Public voidsetmodifydate (Date modifydate) { This. modifydate =modifydate; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; } @Override PublicString toString () {return"Commodity [id=" + ID + ", createdate=" + CreateDate + ", describe=" + describe + ", modifydate=" + modifyd Ate + ", name=" + name + "]"; }        }

Hibernate.cfg.xml:

<?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>        <!--database connection four items Driverclass,url,username,password -        < Propertyname= "Hibernate.connection.driver_class">Com.mysql.jdbc.Driver</ Property>        < Propertyname= "Hibernate.connection.url">Jdbc:mysql://localhost:3306/qsx_shop?characterencoding=utf-8</ Property>        < Propertyname= "Hibernate.connection.username">Root</ Property>        < Propertyname= "Hibernate.connection.password">Root</ Property>                <!--Hibernate dialect, Hibernateh generates corresponding SQL statements based on the configured dialect -        < Propertyname= "Hibernate.dialect">Org.hibernate.dialect.MySQLDialect</ Property>                <!--whether to display SQL -        < Propertyname= "Hibernate.show_sql">True</ Property>                <!--whether to format SQL -        < Propertyname= "Hibernate.format_sql">True</ Property>                <!--Configure Data entity classes -        <Mappingclass= "Online.shixun.model.Commodity" />    </session-factory></hibernate-configuration>

DAO:

 Packageonline.shixun.test;//import java.sql.Date;Importjava.util.Date;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;ImportOrg.hibernate.boot.registry.StandardServiceRegistry;ImportOrg.hibernate.boot.registry.StandardServiceRegistryBuilder;Importorg.hibernate.cfg.Configuration;Importonline.shixun.model.Commodity; Public classHibernatedemo { Public Static voidMain (string[] args)throwsParseException {//Get configuration fileConfiguration Configuration =NewConfiguration (). Configure (); //registering a service objectStandardserviceregistrybuilder Serviceregistrybuilder =NewStandardserviceregistrybuilder (); Standardserviceregistry Serviceregistry=serviceregistrybuilder.applysettings (Configuration.getproperties ()). build (); //Get SessionfactorySessionfactory sessionfactory =configuration.buildsessionfactory (serviceregistry); //Get SessionSession session =sessionfactory.opensession (); //Open Transactionsession.begintransaction (); //************ start Operation *************//        //1. Get the user data with ID 1 using the Get methodCommodity getcommodity = (commodity) session.get (commodity.class, 1); System.out.println ("Date Created:" + getcommodity.getcreatedate () + "description:" + getcommodity.getdescribe () + "Date Modified:" + getcommodity.getmodifydate () + "name :" +getcommodity.getname ()); //Date date = new Date (0);String stringdate = "2019-05-07"; Date Date=NewSimpleDateFormat ("Yyyy-mm-dd"). Parse (stringdate); //2. Adding goods//Commodity newcommodity = new Commodity (date, "Electrical 1", date, "Rice cooker 2");//Session.save (newcommodity); //3. By deleting//Commodity getCommodity1 = (commodity) session.load (Commodity.class, 2);//Session.delete (getCommodity1);//session.gettransaction (). commit (); //4. Change//Commodity getCommodity2 = (commodity) session.get (Commodity.class, 1);//getcommodity2.setname ("wash basin");//session.update (getCommodity2);//session.gettransaction (). commit (); //************ End Operation *************//                        //Commit a transactionsession.gettransaction (); //Close SessionSession.close (); //Close SessionfactorySessionfactory.close (); }}

Hibernate profiles are loaded in the following two ways, as follows:

Use the following statement to load the default Hibernate profile (name: Hibernate.cfg.xml)

Configuration configuration = new configuration (). Configure ();
If you want to customize the Hibernate profile name, you need to use the following statement to load the configuration file

Configuration configuration = new configuration (). Configure ("My-hibernate.cfg.xml");

hibernate--Simple increase, delete, change, check operation

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.