A small demo before Java's spring study

Source: Internet
Author: User

Write this small demo, is to learn spring before the practice of the traditional Model2 development model;

To streamline the process, it is omitted to use Servlets to get foreground data.

A direct new object is given to the program to process, then perform the operation on the database and display (console display, haha).

Used: Hibernate, Reflex, Junit.

First, a project directory diagram, look at the structure:

------------------------------------------------------------

------------------------------------------------------------

1. Build a table to connect to the database and build a persistence class

The generated user class and XML file are placed under the model package

1  Public classUserImplementsjava.io.Serializable {2     PrivateInteger ID;3     PrivateString name;4     PrivateInteger age;5     //Constructors6     /**default constructor*/7      PublicUser () {8     }9     /**Full constructor*/Ten      PublicUser (String name, Integer age) { One          This. Name =name; A          This. Age =Age ; -     } -     //Property Accessors the      PublicInteger getId () { -         return  This. ID; -     } -      Public voidsetId (Integer id) { +          This. ID =ID; -     } +      PublicString GetName () { A         return  This. Name; at     } -      Public voidsetName (String name) { -          This. Name =name; -     } -      PublicInteger getage () { -         return  This. Age; in     } -      Public voidsetage (Integer age) { to          This. Age =Age ; +     } - @Override the      PublicString toString () { *         return"User [id=" + ID + ", name=" + name + ", age=" + Age + "]"; $     }Panax Notoginseng}

It can be seen that a standard javabean,id adopts self-increment (increment).

Another Hibernatesessionfactory file (factory file) is placed under Hibernate package.

2. Create a Userdao interface

The interface is located under the DAO package and prepares for the subsequent method reflection.

1  Public Interface Userdao {2      Public void NewUser (); 3 }

A few three lines of code, but significant!!! I'll see you in the back.

3. Create a class to implement the Userdao interface and customize the user method

1  Public classUsertodoImplementsUserdao {2     //the NewUser () method derives from the method of implementing the interface3      Public voidNewUser () {};4     //custom user-added method, passing in a user object as a parameter5      Public voidAdd (user user) {6         //use Hibernate's factory class to get session objects and transaction objects transaction7Session session =hibernatesessionfactory.getsession ();8Transaction Transaction =session.begintransaction ();9         //Database Add user ActionTen session.save (user); One         //Commit a transaction A transaction.commit (); -         //Close Session Object - session.close (); the     } -     //custom user Query method, passing in a user object ID as a parameter -      Public voidQueryuser (intID) { -         //use Hibernate's factory class to get session objects and transaction objects transaction +Session session =hibernatesessionfactory.getsession (); -         //Transaction Transaction = session.begintransaction (); +         //query the appropriate user based on ID AUser user = (user) session.get (user).class, id); at         //Close Session Object - session.close (); -         //print this acquired object to the console -System.out.println ("The following is the user information for the ID" +id+ "+user.tostring ()); -     } -}

DAO layer implementation of the database additions and deletions to the operation, the method is defined by the service layer to invoke, this demo in the DAO layer only write add users, query

The user's method. will be called at the back of the service layer (DAO layer method will not change normally unless the requirements change)

This class is located in the Daoimp package.

4. The service layer simulates the operation of the user

Call the service layer method when the user clicks on the page

1  Public classUserService {2     StaticUsertodo A;3 4     //using method reflection to get the instantiated object A of the Usertodo class5     private static void init () {6         Try {7Userdao user =NewUsertodo ();8Class C =User.getclass ();9A =(Usertodo) c.newinstance ();Ten}Catch(Exception e) { One e.printstacktrace (); A         } -     }; -  the     //the method by which the object is instantiated to invoke the DAO layer -     //Add User -     Public static void useradd (User newuser) { - init (); + A.add (newuser); -     } +  A     //Query Users at     Public static void userquery (int ID) { - init (); - A.queryuser (ID); -     } -}

initialization function init () Gets the DAO layer object, which is the object that owns the rights to the database operation, and then invokes the method of the object to implement the user's indirect

The operation of the database, which is located under the service package.

5. Unit Testing

1  Public classTest1 {2 @Test3      Public voidAdd () {4User NewUser =NewUser ("Orange Mulberry", 26);5 Userservice.useradd (newuser);6     }7 8 @Test9      Public voidquery () {TenUserservice.userquery (5); One     } A}

The two methods of this test class, the Add () and the Query () methods:

Add () Method: Implements an object that is passed in and then adds the object to the database;

Query () method: the implementation of the user ID number and print user information;

The Add () method executes 9 times and adds 9 users to the table:

--------------------------------------------------------------

---------------------------------------------------------------

Next, execute the query () method, querying for user information with ID 5:

--------------------------------------------------------------------------------

--------------------------------------------------------------------------------

You can see that the console has also successfully exported user information with ID 5.

bingo~~~~~

A small demo before Java's spring study

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.