Java EE Development Framework Building (6)-Complete the basic DAO package with Hibernate4

Source: Internet
Author: User
Tags iterable

Now there are many ORM frameworks, such as guzz,hibernate,mybaits ...., we can choose one when we encapsulate a frame, we can choose a variety of implementations for later use, here I only implemented hibernate, directory structure diagram is as follows:

1. First query Baserepository This interface, the interface generic: T represents the entity type, the ID represents the primary key type, although in the framework has provided the structure of the query searchable, but searchable can not be infinitely powerful, such as a multi-variable correlation query, Nested queries do not have the means to complete, all can only write their own SQL statements, but hibernate write SQL statements can only be written in Java code, with mybaits friends know that SQL statements can be configured in the XML, Here we can simply imitate the mybaits to complete, in this interface provides the call XML in the SQL statement method, specifically how to implement the following description:

Package Com.hqhop.framework.common.orm;///import .../** * <p> * Abstract DAO layer base class provides some easy ways <br/> * <p/> * <s Pan style= "color: #ff0000;" > Generics: T denotes entity type, ID denotes primary key type </span> * <p> * version:1.0 * * @author SILENTWU */public Interface baserepository& Lt T extends Abstractentity<id>, ID extends serializable> extends Pagingandsortingrepository<t, id> {/** * based on  PRIMARY KEY Delete * * @param ids */public void Delete (ID ... ids)/** * Search all conditions by criteria + pagination + sort * * @param searchable * @return */public Page<t> FindAll (searchable searchable);/** * count all records according to criteria * * @param searchable * @return */public Long Count (searc Hable searchable);p ublic void Update (T entity)/** * Custom SQL UPDATE * * @param sqlkey * @param params */public void update (Stri Ng Sqlkey, Object ... params);/** * Custom SQL query * * @param sqlkey * @param params * @return */public list<t> findAll (St Ring Sqlkey, Object ... params);p ublic page<t> findpage (pageable pageable, String sqlkey, Object ... params);/** *Custom SQL Delete * * @param sqlkey * @param params */public void Delete (String sqlkey, Object ... params);} 

The interface inherits the spring's Pagingandsortingrepository interface, but Pagingandsortingrepository inherits the Crudrepository interface, So Baserepository has the basic additions and deletions and some of its own definition of 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 look at Baserepository implementation class Baserepositoryimpl, because to use hibernate to operate the database, so to provide a session, in Hibernate4 has been recommended to directly use the session to manipulate the database, It is not recommended to use hibernatetemplate; to use Sessionfactory.getcurrentsession () to get the session in the current thread, you must open things, So add the following code to the Spring-config.xml:

<!--open annotation transactions are valid only for the current profile--><tx:annotation-driven transaction-manager= "TransactionManager" Proxy-target-class= "true"/><!--Configure Hibernate transaction manager--><bean id= "TransactionManager" class= " Org.springframework.orm.hibernate4.HibernateTransactionManager "><property name=" sessionfactory "ref=" Sessionfactory "/></bean>
In Baserepositoryimpl, you can use the following code:

@Autowiredprivate sessionfactory sessionfactory;public Session getsession () {//transaction must be on (Required) or not get return Sessionfactory.getcurrentsession ();}
3. In Baserepositoryimpl, you must also have a class attribute that specifies the entity class at run time Baserepositoryimpl operation, because SQL queries or HQL queries are made in Hibernate. The results of the query are converted to entity classes by reflection to return to the service. So how do you assign a value to this class object? Here we need to define an annotation repository, which in this note records the entity classes that Baserepositoryimpl to manipulate:

/** *  * @author SILENTWU * * */@Target (Elementtype.type) @Retention (retentionpolicy.runtime) @ Documented@org.springframework.stereotype.repositorypublic @interface Repository {/** * Repository instance name in spring container */ String value () default "";/** * Repository processing entity class *  * @return */class<?> entity ();}
Next we can get this annotation directly in Baserepositoryimpl to get the class, and add the following code to the 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.Format (COUNT_QUERY_ STRING, Clazz.getname ()); this.findallql = String.Format (find_query_string, Clazz.getname ());} else {throw new Exception (Repository.class + "annotation entity cannot be empty!");}} else {throw new Exception (This.getclass () + "must use" + Repository.class + "Annotations!");}}
A @postconstruct annotation is added above the init () method to represent the method to be executed after the class is instantiated by the spring container, or to implement the spring Initializingbean interface to achieve the same effect ( But spring has not recommended this way)

4. In the previous section, we provided a tombstone interface logicdeleteable, the implementation of the logical deletion is in the Baserepositoryimpl, in the Baserepositoryimpl to provide a number of delete methods, But the primary delete operation has only one delete (T entity), and the other deletes are called this:

/** * Check whether the logical delete 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 the object is deleted, first determine whether the Logicdeleteable interface is implemented, if True ==> call markdeleted (); Otherwise the actual deletion.

5. How to use the User entity class Baserepository,baserepositoryimpl:

Interface Userdao

Public interface Userdao extends Baserepository<user, string> {}
Implement class Userdaoimpl, use @repository annotations, specify entity classes for actions

@Repository (entity = user.class) public class Userdaoimpl extends Baserepoitoryimpl<user, string> implements Userdao {}













Java EE Development Framework Building (6)-Complete the basic DAO package with Hibernate4

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.