Preface
The blogger is an undergraduate at second-rate university. I learned about ajax in March 17, 2014, jQuery, And I was touched by the hibernate + spring architecture.
2. Experience in Hibernate + Spring Architecture
Preface:
As we all know, the architecture of a web project is very important. An excellent architecture not only enables the system to run smoothly, but also greatly improves the programmer's understanding and mastery of web engineering.
Architecture hierarchy:Generally, a person who has finished learning Struts + Hibernate + Spring can come up with a general framework, which is generally divided into Entity layers: bean, model, domain, and so on, but all represent the same meaning, it is a symbol of an object. Persistence interface layer: It is generally called Dao, where the general operations on the database are abstracted and defined as the interface layer (add, delete, modify, query, and so on ). Persistence Implementation Layer: generally called DaoImpl, which implements the interface layer and is responsible for the real persistent access function. Business logic layer: generally used as the service layer. The business logic layer component depends on the underlying Dao component (namely the HIbernteaDao layer). This layer focuses on providing business logic functions, persistent access is not involved. Key-value Layer: generally compared with vo layer or dto, it indicates that the previously defined object is only used for data transmission. Web layer: It is generally called a web layer. It is the place where the front-end accesses and calls business logic components, and is also the most complex core of operations. Complete the operations and responses at the front-end. The reason why I wrote this blog today is that this small album project has a new idea of my architecture. We can clearly see the album package layering. Among them, Z branch? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> keys/keys + 21NOm18W8/keys + G4 + keys/qvekjuw.vc3ryb25np1_vadq + keys + release + release/Y8L3A + release + CjwvcD4KPHA + release + jqLTLz + release/ejrLT6wuvI58/CPHByZSBjbGFzcz0 = "brush: java; ">/*** interface of the common DAO component. The seven common methods are the * @ author administrator **/public interface BaseDao that all DAO components should provide. {/*** Load object by ID * @ param entityClazz entity Class * @ param entityId entity ID */T get (Class EntityClazz, Serializable entityId);/*** save entity * @ param entity */Serializable save (T entity ); /***** update entity * @ param entity */void update (T entity);/***** delete entity * @ param entity */void delete (T entity ); /*** delete entity by ID * @ param entityClazz entity Class * @ param entityId entity Id */void delete (Class EntityClazz, Serializable entityId);/*** delete an object by ID array * @ param entityClazz object Class * @ param entityIds Object Id array */void delete (Class EntityClazz, Serializable [] entityIds);/*** obtain all entities * @ param entityClazz entity class */List GetAll (Class EntityClazz);/***** obtain the total number of entities * @ param entityClazz entity Class * @ return */Long getCount (Class EntityClazz );}Org. common. dao. impl. BaseDaoHibernate4 is the basic implementation of various operations. below is the code
/*** Common DAO component implementation class * @ author administrator ** @ param
*/Public class BaseDaoHiberante4
Implements BaseDao
{/*** SessionFactory component */private SessionFactory sessionFactory dependent on the underlying persistence operation of the DAO component;/*** No parameter constructor */public BaseDaoHiberante4 () {// TODO Auto-generated constructor stub} @ SuppressWarnings ("unchecked") @ Overridepublic T get (Class
EntityClazz, Serializable entityId) {// TODO Auto-generated method stubreturn (T) this. getSessionFactory (). getCurrentSession (). get (entityClazz, entityId) ;}@ Overridepublic Serializable save (T entity) {// TODO Auto-generated method stubreturn this. getSessionFactory (). getCurrentSession (). save (entity) ;}@ Overridepublic void update (T entity) {// TODO Auto-generated method stubthis. getSessionFactory (). getCurrentSession (). saveOrUpdate (entity) ;}@ Overridepublic void delete (T entity) {// TODO Auto-generated method stubthis. getSessionFactory (). getCurrentSession (). delete (entity) ;}@ Overridepublic void delete (Class
EntityClazz, Serializable entityId) {// TODO Auto-generated method stubdelete (entityClazz, new Serializable [] {entityId});} @ Overridepublic void delete (Class
EntityClazz, Serializable [] entityIds) {// TODO Auto-generated method stub // traverse and delete for (Serializable serializable: entityIds) {delete (get (entityClazz, serializable ));}} @ Overridepublic List
GetAll (Class
EntityClazz) {// TODO Auto-generated method stubreturn find ("select en from" + entityClazz. getSimpleName () + "en") ;}@ SuppressWarnings ("rawtypes") @ Overridepublic Long getCount (Class
EntityClazz) {// TODO Auto-generated method stubList list = find ("select count (*) from" + entityClazz. getSimpleName (); // The total number of objects obtained by the query, increasing the legality judgment if (list! = Null & list. size () = 1) {return (Long) list. get (0);} return (long) 0;}/*** query the object by HQL statement * @ param hql * @ return */@ SuppressWarnings ("unchecked") protected List
Find (String hql) {return (List
) This. getSessionFactory (). getCurrentSession (). createQuery (hql ). list ();}/*** query the entity * @ param HQL * @ param params * @ return */@ SuppressWarnings ("unchecked") protected List based on the hql statement with the placeholder Parameter
Find (String hql, Object... params) {// create a Query query = this. getSessionFactory (). getCurrentSession (). createQuery (hql); // set the for (int I = 0, len = params) parameter for the HQL statement containing placeholders. length; I <len; I ++) {query. setParameter (I, params [I]);} return (List
) Query. list ();} /*** use the HQL statement for paging query operation * @ param hql the HQL statement to be queried * @ param pageNo query the pageNo page record * @ param pageSize the number of records to be displayed on each page * @ return */@ SuppressWarnings ("unchecked ") protected List
FindByPage (String hql, int pageNo, int pageSize) {// create a query return this. getSessionFactory (). getCurrentSession (). createQuery (hql ). setFirstResult (pageNo-1) * pageSize ). setMaxResults (pageSize ). list ();} /*** use the HQL statement for paging query operation * @ param hql the HQL statement to be queried * @ param pageNo query the pageNo page record * @ param pageSize the number of records to be displayed on each page * @ param params if hql has a placeholder parameter, params is used to input the placeholder * @ return */@ SuppressWarnings ("unchecked") protected List
FindByPage (String hql, int pageNo, int pageSize, Object... params) {// create a Query query = this. getSessionFactory (). getCurrentSession (). createQuery (hql); for (int I = 0, len = params. length; I <len; I ++) {query. setParameter (I, params [I]);} // executes the page and returns the return query result. setFirstResult (pageNo-1) * pageSize ). setMaxResults (pageSize ). list ();} public SessionFactory getSessionFactory () {return sessionFactory;} public void setSessionFactory (SessionFactory sessionFactory) {this. sessionFactory = sessionFactory ;}}
The above code should be handled if you have any learning experience. I will not explain it here.
(2) Special
Because the project is alubm, to better fit the project itself, org. album. dao and org. album. dao. impl are available. The following code is used:
UserDao. java is only because the project actually expands its interfaces.
/*** User Dao * @ author administrator **/public interface UserDao extends BaseDao
{/*** Search for the User name * @ param name: the User name to be searched for * @ return: the User */User findByName (String name );}
Next, org. album. dao. impl. UserDaoHibernate. java
/*** Implementation class code of the UserDao component * @ author administrator **/public class UserDaoHibernate extends BaseDaoHiberante4
Implements UserDao {@ Overridepublic User findByName (String name) {// TODO Auto-generated method stubList
Users = find ("select u from User u where u. name =? ", Name); if (users! = Null & users. size () = 1) {return users. get (0);} return null ;}}
Service Layer:
In the Service layer, the interface and implementation are separated to a greater extent. The following is org. album. service. AlbumService. java
/*** The business logic component depends on the underlying DAO component. The DAO component is responsible for providing the persistent access function *, the business logic component focuses on providing the business logic function * @ author administrator **/public interface AlbumService {/*** to verify whether the user logon is successful. * @ Param name: username for Logon * @ param pass: logon password * @ return: logon result. true is returned If logon is successful. Otherwise, false */boolean userLogin (String name, string pass ); /*** register a new user ** @ param name username for new registration * @ param pass password of the new registered user * @ return primary key of the newly registered user */int registUser (String name, string pass ); /*** Add a photo ** @ param user add a photo user * @ param title add the photo title * @ param fileName add the name of the photo on the server * @ return Add the primary key of the new photo */int addPhoto (String user, string title, String fileName ); /*** obtain all photos of the user based on the user * @ param user current user * @ param pageNo page number * @ return returns the photos of the user/specified page */List
GetPhotoByUser (String user, int pageNo);/*** verify whether the user name is available, check whether the user name * @ param name already exists in the Database. * @ return returns true if the user name is available. Otherwise, false */boolean validateName (String name) is returned );}
The following is the implementation of AlbumServiceImpl. java.
/*** @ Author administrator **/public class AlbumServiceImpl implements AlbumService {/*** DAO component on which the business component depends */private UserDao userDao = null; /*** DAO component on which the business component depends */private PhotoDao photoDao = null; @ Overridepublic boolean userLogin (String name, String pass) {try {// use UserDao to query User user User = userDao by user name. findByName (name); if (user! = Null & user. getPass (). equals (pass) {return true;} return false;} catch (Exception e) {// TODO: handle has tione. printStackTrace (); throw new AlbumException ("handling user logon exceptions") ;}@overridepublic int registUser (String name, String pass) {// TODO Auto-generated method stubtry {// create a new User instance User = new user (); User. setName (name); user. setPass (pass); // userDao for persistent data. save (user); return user. getId ();} catc H (Exception e) {// TODO: handle has tione. printStackTrace (); throw new AlbumException ("new user Registration exception") ;}@overridepublic int addPhoto (String user, String title, String fileName) {// TODO Auto-generated method stubtry {// create a new Photo instance Photo photo = new Photo (); photo. setTitle (title); photo. setFileName (fileName); photo. setUser (userDao. findByName (user); // persistent Photo instance photoDao. save (photo); return photo. getId ();} Catch (Exception e) {// TODO: handle finished tione. printStackTrace (); throw new AlbumException ("an Exception occurred when adding a photo! ") ;}@ Overridepublic List
GetPhotoByUser (String user, int pageNo) {// TODO Auto-generated method stubtry {List
Photos = photoDao. findByUser (userDao. findByName (user), pageNo); List
Result = new ArrayList
(); For (Photo photo: photos) {result. add (new PhotoHolder (photo. getTitle (), photo. getFileName ();} return result;} catch (Exception e) {// TODO: handle has tione. printStackTrace (); throw new AlbumException ("an exception occurred while querying the photo List"); }}@ Overridepublic boolean validateName (String name) {// TODO Auto-generated method stubtry {// query the User instance User = userDao based on the user name. findByName (name); if (user! = Null) {return false;} return true;} catch (Exception e) {// TODO: handle has tione. printStackTrace (); throw new AlbumException ("an exception occurred during user name verification");} public UserDao getUserDao () {return userDao;} public void setUserDao (UserDao userDao) {this. userDao = userDao;} public PhotoDao getPhotoDao () {return photoDao;} public void setPhotoDao (PhotoDao photoDao) {this. photoDao = photoDao ;}}
Key value Layer:
The key-value layer is only used for data transmission. The following are org. album. vo
/*** @ Author administrator **/public class PhotoHolder {/*** photo name */private String title; /*** File Name of the photo on the server */private String fileName;/*** No parameter constructor */public PhotoHolder () {}/*** initialize the constructor * @ param title * @ param fileName */public PhotoHolder (String title, String fileName) {this. title = title; this. fileName = fileName;} public String getTitle () {return title;} public void setTitle (String title) {this. title = title;} public String getFileName () {return fileName;} public void setFileName (String fileName) {this. fileName = fileName ;}}
Web layer:
Here is the intersection of front-end requests and business logic. The processing of the business logic will not be posted