J2EE development framework (6) and j2ee development framework

Source: Internet
Author: User
Tags iterable

J2EE development framework (6) and j2ee development framework

There are many orm frameworks, such as guzz, hibernate, and mybaits ...., when encapsulating a framework, we can choose one or more implementations for future use. Here I only implement hibernate, And the directory structure is as follows:

1. first, query the BaseRepository interface. This interface is generic: T indicates the object type, and ID indicates the primary key type. Although the Searchable structure of the query is provided in the framework, however, Searchable cannot be infinitely powerful. For example, for a variable join query, nested queries cannot be completed, and all queries can only be compiled by themselves, however, only SQL statements written in hibernate can be written in java code. Friends who have used mybaits know that SQL statements can be configured in xml. Here we can simply follow mybaits to complete the process, this interface provides a method to call SQL statements in xml. The specific implementation is described later:

Package com. hqhop. framework. common. orm; // import ..... /*** <p> * provides some simple methods to abstract the base classes of DAO layers <br/> * <p/> * <span style = "color: # ff0000; "> generic: T indicates the entity type; ID indicates the primary key type </span> * <p> * Version: 1.0 ** @ author silentwu */public interface BaseRepository <T extends actentity <ID>, ID extends Serializable> extends PagingAndSortingRepository <T, ID> {/*** delete by primary key ** @ param ids */public void delete (ID... ids);/*** query all conditions by condition + paging + sorting ** @ param searchable * @ return */public Page <T> findAll (Searchable searchable ); /*** count all records based on the condition ** @ param searchable * @ return */public long count (Searchable searchable); public void update (T entity ); /*** custom SQL update ** @ param sqlKey * @ param params */public void update (String sqlKey, Object... params);/*** custom SQL query ** @ param sqlKey * @ param params * @ return */public List <T> findAll (String sqlKey, Object... params); public Page <T> findPage (Pageable pageable, String sqlKey, Object... params);/*** delete custom SQL ** @ param sqlKey * @ param params */public void delete (String sqlKey, Object... params );}

This interface inherits the PagingAndSortingRepository interface of spring. However, PagingAndSortingRepository inherits the CrudRepository interface. Therefore, BaseRepository has the following basic methods:

@NoRepositoryBeanpublic interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {Iterable<T> findAll(Sort sort);Page<T> findAll(Pageable pageable);}
@NoRepositoryBeanpublic interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {<S extends T> S save(S entity);<S extends T> Iterable<S> save(Iterable<S> entities);T findOne(ID id);boolean exists(ID id);Iterable<T> findAll();Iterable<T> findAll(Iterable<ID> ids);long count();void delete(ID id);void delete(T entity);void delete(Iterable<? extends T> entities);void deleteAll();}
2. next, check the implementation class BaseRepositoryImpl of BaseRepository. To use hibernate to operate the database, we recommend that you use session directly in hibernate4 to operate the database. We recommend that you do not use hibernateTemplate; to use sessionFactory. getCurrentSession () to get the session in the current thread must enable the thing, so Add the following code in the spring-config.xml:

<! -- Enable annotation transactions only for the current configuration file --> <tx: annotation-driven transaction-manager = "transactionManager" proxy-target-class = "true"/> <! -- Configure the Hibernate Transaction Manager --> <bean id = "transactionManager" class = "org. springframework. orm. hibernate4.HibernateTransactionManager "> <property name =" sessionFactory "ref =" sessionFactory "/> </bean>
The following code can be used in BaseRepositoryImpl:

@ Autowiredprivate SessionFactory sessionFactory; public Session getSession () {// the transaction must be enabled (Required); otherwise, return sessionFactory. getCurrentSession ();} cannot be obtained ();}
3. you must also have a Class attribute in BaseRepositoryImpl to specify the entity Class for the BaseRepositoryImpl operation at the runtime, because SQL queries or hql queries are performed in hibernate, the query result is converted to an object class through reflection and returned to the service. So how can we assign values to this Class object? Here we need to define a Repository annotation. In this annotation, the entity class to be operated by BaseRepositoryImpl is recorded:

/***** @ Author silentwu **/@ Target (ElementType. TYPE) @ Retention (RetentionPolicy. RUNTIME) @ Documented@org.springframework.stereotype.Repositorypublic @ interface Repository {/*** Repository Instance name in the spring container */String value () default ""; /*** entity Class processed by Repository ** @ return */Class <?> Entity ();}
Next we can get this annotation directly in BaseRepositoryImpl to get the Class, and add the following code in BaseRepositoryImpl:

Private Class <T> clazz; @ PostConstruct @ SuppressWarnings ("unchecked") public void init () throws Exception {<span style = "color: # ff0000; "> Repository repository = this. getClass (). getAnnotation (Repository. class); </span> if (Utils. isNotEmpty (repository) {if (Utils. isNotEmpty (repository. entity () {<span style = "color: # ff0000;"> this. clazz = (Class <T>) repository. entity (); </span> this. countAllQL = String. forma T (COUNT_QUERY_STRING, clazz. getName (); this. findAllQL = String. format (FIND_QUERY_STRING, clazz. getName ();} else {throw new Exception (Repository. the entity of class + "annotation cannot be blank! ") ;}} Else {throw new Exception (this. getClass () +" must use "+ Repository. class +" annotation! ");}}
Added the @ PostConstruct Annotation on the init () method to indicate the method to be executed after the class is instantiated by the spring container; you can also implement the spring InitializingBean interface to achieve the same effect (but this method is not recommended for spring)

4. in the previous chapter, we provided the logical deletion interface LogicDeleteable. The specific implementation logic is deleted in BaseRepositoryImpl, and multiple deletion methods are provided in BaseRepositoryImpl, however, the main delete operation only has one delete (T entity), and other delete operations call this:

/*** Check whether the logical deletion interface is implemented ** @ return */private boolean checkLogicDeleteable () {Class [] inters = this. clazz. getInterfaces (); boolean flag = false; for (int I = 0; I <inters. length; I ++) {if ("LogicDeleteable ". equals (inters [I]. getSimpleName () {flag = true; break ;}} return flag ;}@ Overridepublic void delete (T entity) {if (Utils. isNotEmpty (entity) {if (entity instanceof LogicDeleteable) {(LogicDeleteable) entity ). markDeleted (); update (entity);} else {this. getSession (). delete (entity );}}}
When deleting an object, first determine whether the LogicDeleteable interface is implemented. If it is true => call markDeleted (); otherwise, delete the object.

5. Use BaseRepository and BaseRepositoryImpl to operate the User object class:

Interface UserDao

public interface UserDao extends BaseRepository<User, String> {}
Implementation class UserDaoImpl. Use the @ Repository annotation to specify the object class of the operation

@Repository(entity = User.class)public class UserDaoImpl extends BaseRepoitoryImpl<User, String> implements UserDao {}














Q: The development framework and development environment are two different things. The development framework, such as J2EE, has already defined the underlying structure in advance. Is the development environment developed from the underlying layer?

First, the development environment is a very broad concept. For example, the operating systems, development tools, JDK versions, databases, and SVN version control servers you use during development can all be called your development environment in a broad sense. In some specific language context environments, development environments may have narrow concepts. For example, if a software company uses the IBM Portal product for development, the project manager says, "XXX, did you set up the development environment yesterday ?" Here, the development environment refers to the establishment of the company's IBM Portal development environment.
Framework, software semi-finished products, for the reuse of a specific function (more technical), the code and framework designer's good design pattern reusable code set. When developing specific applications, in order to focus more attention on complex requirements and business processing, we can choose to use some frameworks to help us implement some specific functional requirements and code reuse, Design Pattern Reuse requirements.
In software, software semi-finished products can be divided into framework component middleware according to the granularity.

Guaner training-Whampoa Military School for Java 3G engineer Employment Training

J2EE: How can I build a j2ee environment using eclipse + atat6036 + jdk7u7 + oracle11g? Does eclipse have a j2ee version?

Problem 1: With eclipse, you do not need to use myeclipse again, but you need to configure it when allowing the project

Question 2: All myeclipse should have jdk, but we recommend that you use jdk for official development.

Question 3: I have not studied this. I personally feel that it is better to explore it myself. If I have a development foundation, it is actually relatively simple.

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.