1. In this I would like to first talk about the creation of the session object, this is the core object we manipulate the database, so first we should get the corresponding session object.
Public StaticConfiguration cfg; Public StaticSessionfactory Factory; Public StaticSession session =NULL; Static { //the configuration file used to read the Hibernate.cfg.xmlCFG =NewConfiguration (). Configure (); //Get FactoryFactory =cfg.buildsessionfactory (); //create a corresponding Session objectSession =factory.opensession (); }
It is emphasized that static is used here to ensure that we generate only one session without repeated calls.
2. The save operation is then done, and the data object is saved.
Public Static void insertstudentselection (String studentid,string teacherid) { session.begintransaction (); // Open Transaction Studentselection st=New studentselection (studentid,teacherid); Session.save (ST); Session.gettransaction (). commit (); // data is saved successfully after committing a transaction session.close (); }
The open transaction here is necessary, if we do not open the transaction and save the transaction, our corresponding database save operation will fail, and the establishment of the session should be closed after use, otherwise long-term use will cause connection pool overflow and other problems, Hibernate does not have the ability to automatically commit transactions like JDBC, so we have to manually open and commit.
3. At the time of the submission of the object, I have a problem, is duplicate entry ' ABC ' for key ' PRIMARY ' error, this reason in the data I inserted with the primary key and the database exists data duplication, so the database refused to insert, the next time it is necessary to pay attention to.
4. Same as I also query operation of the database
Public Static BooleanSelect (Student stu) {session.begintransaction ();//Open TransactionCriteria cre = Session.createcriteria (Student.class); Cre.add (Expression.eq ("StudentID", Stu.getstudentid ())); Cre.add (Expression.eq ("Password", Stu.getpassword ())); List<Student> Student =cre.list (); if(Session.isopen ()) {//Close TransactionSession.close (); } //list<student> Student = Session.createcriteria (Student.class). Add (//example.create (Stu)). List (); for(Student stu1:student) {System.out.println (STU1); } //when the discovery set is empty, it proves to be a query to the corresponding data if(Student.isempty ()) {return false; } Else { return true; } }
Through the list collection I can get back the corresponding collection of objects and iterate through the foreach statement.
Hibernate Simple Save operation