Resolves an issue where hibernate can only insert one piece of data

Source: Internet
Author: User

Hibernate beginner, according to the video tutorial write Good code, found no matter how many times the main function, the database only one data, try many times, and finally found the problem ...

The tool used is: MYSQL 5.7.13 eclipse 4.5.2 Hibernate 4.0.5

The first step:

Create a new database named DEMO01 in MySQL, and then build a test table:

 Use DEMO01; CREATE TABLE  intvarchar(), Test_date DATE,primarykey  (test_id)) engine=default charset=UTF8 auto_increment=  1;

Step Two:

Create a new Java project, add a persistence class

 PackageCom.hibernate.demo;/** Persistent class test*/Importjava.util.Date; Public classTest {Private intID; PrivateString name; PrivateDate time;  PublicTest () {} Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicDate GetTime () {returnTime ; }     Public voidsettime (Date time) { This. Time =Time ; } @Override PublicString toString () {return"Test [id=" + ID + ", name=" + name + ", time=" + Time + "]"; }    }

Step Three:

Create a mapping file for hibernate, where the name in the property corresponds to the attribute in the persisted class, and the name in column is the field name in 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 2016-8-13 17:46:08 by Hibernate Tools 3.5.0.Final-->< Hibernate-mapping>    <class name= "Com.hibernate.demo.test" table= "Test" >        <id name= "id" type= "int" >            <column name= "test_id"/>            class= "Assigned"/>        </id>        < Property name= "Name" type= "java.lang.String" >            <column name= "name"/>        </property>        < Property name= "Time" type= "Java.util.Date" >            <column name= "test_date"/>        </property>    </class>

Fourth Step:

To create a hibernate configuration file:

<?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" & gt;///demo01?useunicode=true&amp;characterencoding=utf-8</property><property name= "dialect" >org.hibernate.dialect.MySQLDialect</property> <property name= "Show_sql" >true</property> <property name= "Format_sql" >true</property> <property name= "Hbm2ddl.auto" >update</property> <mapping resource= "Com/hibernat E/demo/test.hbm.xml "/> </session-factory>

Hibernate configuration file contents are configured as key-value pairs:

Connection.driver_class refers to the driver of connecting database, different to different relational database, the driver needs to change according to the actual situation;

Connection.url refers to the URL of the corresponding database;

Dialect refers to the corresponding database dialect;

Show_sql refers to whether the program runs in the console output SQL statement, true output, false output. By default false, the debugger is generally set to True when the program is changed to False, because the output SQL statement can affect the running speed of the program;

Format_sql refers to whether the program runs with the output of an SQL statement that facilitates debugging of annotation information. True output, false not output, false by default. This property is valid only if Show_sql is true.

Hbm2dd.auto refers to the type of operation that is performed on the database data:

Create: Recreate the database table structure each time hibernate is loaded

Create-drop: Create when Hibernate is loaded, delete table structure when exiting

Update: Load hibernate automatically updates database structure

Validate: Validating the creation of a database table structure when hibernate is loaded

Well.... My problem is here ... The first is written to create, and later to update it is no problem ... Once the database table is found to be missing, first look at the values set here ...

Fifth Step:

Create session factory and test instances, additions and deletions are available, but may not complete (according to reason should be divided to write, I wrote here together, stole a lazy ~)

 PackageCom.hibernate.demo;Importjava.util.Date;Importjava.util.List;ImportOrg.hibernate.Query;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;ImportOrg.hibernate.boot.registry.StandardServiceRegistry;ImportOrg.hibernate.boot.registry.StandardServiceRegistryBuilder;Importorg.hibernate.cfg.Configuration; Public classTestmanage {Private Static FinalSessionfactory sessionfactory=buildsessionfactory (); Private Staticsessionfactory buildsessionfactory () {//creating a Configuration objectConfiguration cfg =NewConfiguration (). Configure (); //Create a Service registration objectStandardserviceregistrybuilder SRB =NewStandardserviceregistrybuilder (). Applysettings (Cfg.getproperties ()); Standardserviceregistry SR=Srb.build (); //To create a factory Session object        returnCfg.buildsessionfactory (SR); }             Public Static voidMain (string[] args) {Session session=sessionfactory.opensession ();                Session.begintransaction (); //NewTest thetest=Newtest (); Thetest.setname ("Mist332!"); Thetest.settime (NewDate ());                        Session.save (thetest); //Update        /*Test utest=new test ();        Utest.setid (1);//id can not be less, Hibernate is based on the ID to query the data to update the Utest.setname ("The whole universe I am the most handsome ~ ~ ~"); Session.update (utest);*/                //Delete        /*Test dtest=new test ();        Dtest.setid (1);//hibernate first query, then delete test dtest1= (test) Session.get (Test.class, 1);        Session.delete (DTEST1); */                //Enquiry//hql query, is hibernate main push query way, and SQL comparison, but behind the form is the Java class name, not the database table name,//If query full field SELECT * Can omit do not write        /*Query query=session.createquery ("from Test");        List<test> list=query.list ();        for (test t:list) {System.out.println (t.tostring ()); }*/                //when you are not querying the full field, or you are querying data from two tables together, an array is returned:        /*Query query=session.createquery ("Select S.name,t.name from Student s, Test T"); List<object[]> list=query.list ();//each row here is a one-dimensional array for (int i=0;i<list.size (); i++) {Object []o= (o Bject[]) list.get (i);//Transformation the array string name1= (String) o[0];//corresponds to the order type in select, which can be a class string name2= (String            ) o[1];            SYSTEM.OUT.PRINTLN (name in student: "+name1+" in Test, Name: "+name2");        System.out.println ("isolated ~~~~~~~~"); }*/session.gettransaction (). commit ();        Session.close ();    Sessionfactory.close (); }        }

If we set the setting to create, then the SQL executed will be:

INFO:HHH000227:Running HBM2DDLSchemaexporthibernate:Drop Table if existstesthibernate:Create TableTEST (test_idinteger  not NULL, NAMEvarchar(255), Test_datedatetime,        Primary Key(test_id)) August -, . 6: -:GenevaAfternoon Org.hibernate.tool.hbm2ddl.SchemaExportExecuteinfo:hhh000230:SchemaExport completehibernate:Insert      intoTEST (NAME, Test_date, test_id)Values        (?, ?, ?) August -, . 6: -:Genevapm Org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stopinfo:hhh000030: Cleaning up Connection Pool[Jdbc:mysql:///demo01?useunicode=true&characterencoding=utf-8]Insert Success! 

If set to update:

August -, . 6: -: -Afternoon org.hibernate.tool.hbm2ddl.SchemaUpdateExecuteinfo:hhh000232:Schema Updatecompletehibernate:Insert      intoTEST (NAME, test_date)Values        (?, ?) August -, . 6: -: -pm Org.hibernate.engine.jdbc.spi.sqlexceptionhelper$standardwarninghandler logwarningwarn:sql Warning Code: 1292, SQLState:22007August -, . 6: -: -afternoon Org.hibernate.engine.jdbc.spi.sqlexceptionhelper$standardwarninghandler Logwarningwarn:incorrect Date value : '2016-08-13 18:44:24.789'  for column 'test_date'At row1August -, . 6: -: -pm Org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stopinfo:hhh000030: Cleaning up Connection Pool[Jdbc:mysql:///demo02?useunicode=true&characterencoding=utf-8]Insert Success! 

It's easy to see the difference from the printed SQL statement.

Resolves an issue where hibernate can only insert one piece of data

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.