Review generics/inheritance/implementation concepts through Hibernate encapsulation database persistence process

Source: Internet
Author: User
Tags object object

Objective

In the development process, it is not difficult to find that the customer's needs and product positioning for the development of the direction of the content of a great decision-making role, and these often need to be considered in the beginning as thoughtful and well-designed. Why say it as much as we all know, demand this stuff, long story ... As a developer, since it is not possible to control the change of requirements and other factors, we have to grasp the tools we can determine the resources, architecture design, technology selection and so on. Some people may say, I just how long experience and so on, the structure of what is not all leader are the things of the big boys, choose what the database with what technology is not I can decide. If you have this idea, I can only think that you are right. Do not know everyone in the development process, have not encountered, a scene or effect with the existing tool technology you feel that can not be achieved or difficult to achieve, or you know the implementation of the technical framework is not used? Echarts, POI, etc., for me, are consistent with the above scenario. In general, some things can be used as learning in the development process, while others require you to spend extra time outside of work to study. Of course, if you say that you need any new technology in your job, you can master it one day or another, and that's the ability. And it's not sarcasm or anything, it's real, I'm increasingly feeling the importance of learning ability, he has a lot of influence on a person's potential capacity growth curve, of course, you have the ability to not study, it is destined to be a straight shot. Spring, Strus 2, Hibernate, Mybatis, spring MVC are the most common frameworks used for Web projects, and the persistence layer currently includes Hibernate, Mybatis, Spring data JPA, and more. At the moment I'm using spring data JPA, this thing is really powerful, with more than my previous ideas on a step, and with hibernate support is also very good, hibernate itself is the implementation of the JPA specification. The next article in the Project class and method design idea is based on Hibernate, just review, understand the shortcomings, good combined with the JPA improvements now.

Project structure at a glance

Taking the Web project technology framework as an example of spring+hibernate+spring MVC, ignoring configuration and web front end files, background results are mostly streamlined as follows:

Proceed from the database direction in turn:

1.domain layer, the standard interpretation of this thing is the domain model, our ORM Object Relationship mapping entity class is generally placed under the layer, that is, the entity layer, similar to the term, entity, model, Pojo and so on;

2.repository layer, database access layer, this is the DAO layer, the method of storing database access operations;

The 3.service layer, the business logic layer, where the business logic is stored, some people may start to feel that the service layer is unnecessary or unclear, compared to the DAO layer. First about the difference between the two: the business logic layer, so the name of the idea, his important position is business, business needs what, he will provide what, for example, the DAO layer provides you the method of deleting the product and add the log method, the two methods correspond to have two entity object goods and logs, the operation of the database corresponding to a single table , but the reality is that you always feel what is wrong through a single method, the business scenario, if you need to delete things after the corresponding log records, and the log will not be fabricated, need to have events corresponding. At this time, the role of service layer is reflected, simple can understand, complex database processing you rely on a single DAO method can not be implemented, you in the service layer to construct this method, through the SPRINGIOC characteristics, The actual scenario is typically an interface where the service layer injects the class or interface of the DAO method that you need to invoke. Secondly on the necessity, I have also thought, directly inside the controller to inject multiple DAO class or interface can not also achieve the desired effect? The controller, as the name implies, is in the web results, the main role of receiving and forwarding requests and control, when your business logic is relatively simple, you feel that there is not much difference, when the actual project business logic is relatively complex situation, This controller is a bit fried, like a multi-duty overworked labor, in addition to a doubt, there is a very important concept is the transaction, and spring's transaction management is also in place, through programmatic transaction management or declarative transaction management can be achieved, And the transaction is generally set in the business logic is the service layer, about the transaction is also very important and the essence of a piece, need to learn also worth learning.

4.controller layer, control layer, with struts 2 may call the action layer bar, or universal point, called the Web layer can actually also. He can receive a different request URL, call the corresponding service layer code, manipulate the database, jump to the development page, or do not jump, directly return the data, here the data is currently used in JSON more than the typical application scenario: Ajax initiates an asynchronous request, After the Dispatcherservlet captures the request, the URL is parsed and distributed to the corresponding method in the corresponding control class where the code is executed, and the method is added with @responsebody.

about Hibernate's positioning in the project

Hibernate is a typical ORM persistence layer framework, ORM is Object Relational Mapping, which is the relationship mapping between entity classes and database tables, and in layman's words, a table corresponds to an entity class, and a record corresponds to an entity class object. fields correspond to entity class properties. The operation of the database in Hibernate has an important object session, through the session package a series of database operation methods in the database access layer, so in the above structure, hibernate main operations and functions of the domain layer and the repository layer, The following example also omits additional layer code.

Example

Domain layer, here simple to use, MySQL database primary key is also used by the int self-increment, the actual application of large amounts of data, such as a varchar, save using the UUID assignment of the primary key.

1 @Entity2@Table (name= "Tbl_user")3  Public classUser {4     PrivateInteger ID;5     PrivateString username;6     PrivateString password;7 @Id8@GeneratedValue (strategy=Generationtype.auto)9      PublicInteger getId () {Ten         returnID; One     } A      Public voidsetId (Integer id) { -          This. ID =ID; -     } the      PublicString GetUserName () { -         returnusername; -     } -      Public voidSetusername (String username) { +          This. Username =username; -     } +      PublicString GetPassword () { A         returnpassword; at     } -      Public voidSetPassword (String password) { -          This. Password =password; -     } - @Override -      PublicString toString () { in         return"User [id=" + ID + ", username=" + Username + ", password=" + password + "]"; -     } to      +      -      the}

Repository Layer

basedao generic interface

 public  interface  basedao<t>< Span style= "COLOR: #000000" > { public  void<        /span> edit (Object obj); //     public             void  Delete (int  ID); //     public                 T Load (int  ID); //     public                 T Get (int  ID); //  Find a record based on the primary key (not lazy loading) } 

Basedao Generic Implementation Class

 Public classBasedaoimpl<t>ImplementsBasedao<t>{@ResourcePrivateSessionfactory Factory; PrivateClass<t> clazz = Generiscutil.getgenerictype ( This. GetClass ()); protectedSession getsession () {returnfactory.getcurrentsession (); }         Public voidedit (Object obj) {getsession (). saveorupdate (obj); }     Public voidDeleteintID) {Object object=getsession (). Get (Clazz, id); if(Object! =NULL) {getsession (). Delete (object); }    }     PublicT Load (intID) {return(T) getsession (). Load (clazz, id); }     PublicT Get (intID) {return(T) getsession (). Get (Clazz, id); }}

Generic Tool class

 Public classgeneriscutil {@SuppressWarnings ("Rawtypes")     Public Staticclass Getgenerictype (class Clazz) {Type Gentype= Clazz.getgenericsuperclass ();//get generic parent classtype[] Types =((Parameterizedtype) gentype). Getactualtypearguments (); if(! (Types[0]instanceofClass)) {            returnObject.class; }         return(Class) Types[0]; }}

Finally: Userdao interface and Userdaoimpl implementation class

 Public Interface extends Basedao<user> {    User Login (string username, string password);}
@Repository ("Userdao") Public classUserdaoimplextendsBasedaoimpl<user>ImplementsUserdao { PublicUser Login (string username, string password) {string hql= "from User u where U.username=:un and u.password=:p WD"; Query Query=getsession (). CreateQuery (HQL); Query.setstring ("Un", username). setString ("PWD", password); Object obj=Query.uniqueresult (); returnObj! =NULL? (User) obj:NULL; }    }

and its Xxxdao and Xxxdaoimpl, through inheritance and implementation, can make it easy for all IMPL implementation classes to have a basic crud and other common database operations method, if an entity has a special DAO operation that only needs to be implemented on the corresponding DAO interface, Then implement the special method in the Impl implementation class, and the previously recognized knowledge points have a deep understanding here.

Generics are a kind of thought, is also a kind of technology, the dynamic acquisition type, makes the programming more flexible, here the use of generics, we can not make the entity class object concrete type, constructs a generic DAO interface and the implementation class, lets the subsequent concrete entity DAO to inherit the generic type, then determines the type, The basic methods defined in generics are also obtained.

Inheritance embodies the idea of code reuse, when a method is constructed several times we have to think about the problem of code reuse, where each entity object needs a basic database operation method, if one of the definitions will be very tedious and boring, through inheritance we can save a lot of code.

Implementation is different from inheritance, it does not save code, but also involves the concept of abstraction, in the inheritance of a single parent class and multiple subclasses, the parent class of a method corresponding to the subclass of the implementation of the difference, we are the parent class of the method can be defined as an abstract method, subclasses each implementation of specific details can be. For example: Animal parents, sub-species have birds, fish, and so on, define the animals, will define the sleep method, but each animal sleep situation is not the same, birds sleep in the tree, fish sleep under water, you can not specify the specific implementation details, so it is possible to define an abstract sleep method void sleep (); The specific animal implements the interface Override this abstract method to show the implementation details.

Summarize inheritance and implementation: inherit generic, implement special. In the persistence layer constructed in this article, all of our entities easily have all the common database operation methods through inheritance, and their special operational requirements can be life in the respective interfaces and implemented in the implementation class.

Finally, the article in fact there are many deficiencies, the type of the primary key can also be used generics, DAO layer has a generic component, the service layer should also have a common, if there is how to construct and so on, some problems I now use the spring data JPA to get the answer, So it should be another comb to write it out.

Review generics/inheritance/implementation concepts through Hibernate encapsulation database persistence process

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.