Spring General basedao

Source: Internet
Author: User

2.0

Spring applicationContext. xml configuration (example)
<? Xml version = "1.0" encoding = "UTF-8"?>
<Beans
Xmlns = "http://www.springframework.org/schema/beans"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xmlns: tx = "http://www.springframework.org/schema/tx"
Xmlns: aop = "http://www.springframework.org/schema/aop"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
Http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
">
<! -- Create a connection pool -->
<Bean name = "datasouce" class = "org. apache. commons. dbcp. BasicDataSource">
<Property name = "driverClassName" value = "oracle. jdbc. driver. OracleDriver"> </property>
<Property name = "url" value = "jdbc: oracle: thin: @ 127.0.0.1: 1521: orcl"> </property>
<Property name = "username" value = "sa"> </property>
<Property name = "password" value = "sa123456"> </property>
<Property name = "maxActive" value = "100"> </property>
<Property name = "maxIdle" value = "30"> </property>
<Property name = "maxWait" value = "100000"> </property>
<Property name = "defaultAutoCommit" value = "false"> </property>
</Bean>
<Bean name = "sessionFactory" class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean">
<Property name = "dataSource" ref = "datasouce"> </property>
<Property name = "hibernateProperties">
<Props>
<! -- Load the hibernate Configuration Attribute dialect (dialect) show_ SQL (the SQL statement displayed in the database) -->
<Prop key = "hibernate. dialect"> org. hibernate. dialect. Oracle9Dialect </prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
</Props>
</Property>
<! -- Load the hibernate class ing file about the database -->
<Property name = "mappingResources">
<List>
<Value> com/skeyedu/crm/entity/CrmUserandcustomer. hbm. xml </value>
<Value> com/skeyedu/crm/entity/User. hbm. xml </value>
<Value> com/skeyedu/crm/entity/Customer. hbm. xml </value>
<Value> com/skeyedu/crm/entity/CrmCustomerandlinkman. hbm. xml </value>
<Value> com/skeyedu/crm/entity/LinkMan. hbm. xml </value>
<Value> com/skeyedu/crm/entity/Crmfollow. hbm. xml </value>
</List>
</Property>
</Bean>
<! -- All dao implementation classes inherit the sessionFactory attribute in HibernateDaoSupport. -->
<Bean name = "userdao" class = "com. skeyedu. crm. dao. impl. UserDaoImpl">
<Property name = "sessionFactory" ref = "sessionFactory"> </property>
</Bean>
<Bean name = "customerdao" class = "com. skeyedu. crm. dao. impl. CustomerDaoImpl">
<Property name = "sessionFactory" ref = "sessionFactory"> </property>
</Bean>
<Bean name = "linkmandao" class = "com. skeyedu. crm. dao. impl. LinkManDaoImpl">
<Property name = "sessionFactory" ref = "sessionFactory"> </property>
</Bean>
<! -- The service layer calls the dao method and configures the dao interface Attributes -->
<Bean name = "userservice" class = "com. skeyedu. crm. service. impl. UserServiceImpl">
<Property name = "UDao" ref = "userdao"> </property>
</Bean>
<Bean name = "customerservice" class = "com. skeyedu. crm. service. impl. CustomerServiceImpl">
<Property name = "CDao" ref = "customerdao"> </property>
</Bean>
<Bean name = "linkmanservice" class = "com. skeyedu. crm. service. impl. linkManServiceImpl">
<Property name = "CDao" ref = "customerdao"> </property>
<Property name = "LDao" ref = "linkmanao"> </property>
</Bean>
<! -- Scope = "prototype" indicates that each time an action is called, a new object is created. In this way, the error still exists at the value of input, resulting in an error reported by tendon, which cannot be used by other operations, because the same action is used (the underlying mechanism of struts2 is to use new objects) in this case, scope = "prototype" creates a new action object when this type of object is requested. If scope = prototype is not configured, no action will be created during addition, and the information of the last access record will be retained. -->
<Bean name = "douser" class = "com. skeyedu. crm. struts. DoUserAction" scope = "prototype">
<Property name = "UService" ref = "userservice"> </property>
</Bean>
<Bean name = "docustomer" class = "com. skeyedu. crm. struts. DoCustmoerAction" scope = "prototype">
<Property name = "CService" ref = "customerservice"> </property>
<Property name = "UService" ref = "userservice"> </property>
</Bean>
<Bean name = "dolinkman" class = "com. skeyedu. crm. struts. DoLinkmanAction" scope = "prototype">
<Property name = "CService" ref = "customerservice"> </property>
<Property name = "LService" ref = "linkmanservice"> </property>
</Bean>
<! -- Declare a transaction and only manage the service layer. If an exception occurs when the dao layer method is called, capture and roll back the transaction. (For example, Add * indicates the method that begins with the transaction environment management Add ), other methods that do not comply with the following rules are not committed or rolled back. They are read-only and generally do not involve database updates. -->
<Bean name = "trasactionManager"
Class = "org. springframework. orm. hibernate3.HibernateTransactionManager">
<Property name = "sessionFactory" ref = "sessionFactory"> </property>
</Bean>
<Tx: advice id = "myadvice" transaction-manager = "trasactionManager">
<Tx: attributes>
<Tx: method name = "Add *" propagation = "REQUIRED" rollback-for = "Exception"/>
<Tx: method name = "Edit *" propagation = "REQUIRED" rollback-for = "Exception"/>
<Tx: method name = "Del *" propagation = "REQUIRED" rollback-for = "Exception"/>
<Tx: method name = "Drop *" propagation = "REQUIRED" rollback-for = "Exception"/>
<Tx: method name = "Regst *" propagation = "REQUIRED" rollback-for = "Exception"/>
<Tx: method name = "your user *" propagation = "REQUIRED" rollback-for = "Exception"/>
<Tx: method name = "*" read-only = "true"/>
</Tx: attributes>
</Tx: advice>
<! -- Use aop (Aspect-Oriented) to declare which package interface is used for transaction management (column: "execution (* com. skeyedu. crm. service. *. *(..)) "expression: First star: return value, second star: Class, second Samsung: method ,(..): parameter)
Cut: Which of the following interfaces is used for transaction management?
The first asterisk represents the type of the method return value.
The second asterisk represents the interface or class name under the package.
The third asterisk represents the method name of the interface or class under the package.
The two points in parentheses represent arbitrary method parameters -->
<Aop: config>
<Aop: pointcut expression = "execution (* com. skeyedu. crm. service. *. * (..)" id = "mycutpoint"/>
<! -- Merge transactions and aspect -->
<Aop: advisor advice-ref = "myadvice" pointcut-ref = "mycutpoint"/>
</Aop: config>
</Beans>
Spring basedao (General)
Package com. test. mydb;
Import java. io. Serializable;
Import java. SQL. SQLException;
Import java. util. ArrayList;
Import java. util. List;
Import org. hibernate. HibernateException;
Import org. hibernate. Query;
Import org. hibernate. Session;
Import org. springframework. orm. hibernate3.HibernateCallback;
Import org. springframework. orm. hibernate3.support. HibernateDaoSupport;
Public class SpringBasedao extends HibernateDaoSupport {
// Add a single object
Public int save (Object o ){
Int row = 0;
Try {
Super. getHibernateTemplate (). save (o );
Row = 1;
} Catch (Exception e ){
E. printStackTrace ();
}
Return row;
}
// Modify a single object
Public int update (Object o ){
Int row = 0;
Try {
Super. getHibernateTemplate (). clear ();
Super. getHibernateTemplate (). update (o );
Row = 1;
} Catch (Exception e ){
E. printStackTrace ();
}
Return row;
}
// Delete a single object
Public int delete (Class cls, Serializable id ){
Int row = 0;
Object o = get (cls, id );
Try {
Super. getHibernateTemplate (). delete (o );
Row = 1;
} Catch (Exception e ){
E. printStackTrace ();
}
Return row;
}
// Obtain a single object based on the ID (primary key)
Public Object get (Class cls, Serializable id ){
Return getHibernateTemplate (). get (cls, id );
}
// Query the collection of objects and hql query statements
Public List getlistbyhql (String hql ){
List list = new ArrayList ();
List = getHibernateTemplate (). find (hql );
Return list;
}
Public List getlistbyhql (final String hql, final String [] parms ){
List list = new ArrayList ();
Listparts gethibernatetemplate(cmd.exe cuteFind (new HibernateCallback (){
Public Object doInHibernate (Session session)
Throws HibernateException, SQLException {
Query query = session. createQuery (hql );
If (parms! = Null ){
For (int I = 0; I <parms. length; I ++ ){
Query. setString (I, parms [I]);
}
}
Return query. list ();
}
});
Return list;
}
// Query the data volume
Public Object getuniqbyhql (final String hql ){
Object o=gethibernatetemplate(cmd.exe cute (new HibernateCallback (){
Public Object doInHibernate (Session session)
Throws HibernateException, SQLException {
Query query = session. createQuery (hql );
Return query. uniqueResult ();
}
});
Return o;
}
Public Object getuniqbyhql (final String hql, final String [] parms ){
Object o=gethibernatetemplate(cmd.exe cute (new HibernateCallback (){
Public Object doInHibernate (Session session)
Throws HibernateException, SQLException {
Query query = session. createQuery (hql );
If (parms! = Null ){
For (int I = 0; I & lt; parms. length; I ++ ){
Query. setString (I, parms [I]);
}
}
Return query. uniqueResult ();
}
});
Return o;
}
// Execute batch Update (modify and delete)
Public int exeupdatehql (final String hql ){
Int row = 0;
Row#(integer%gethibernatetemplate(cmd.exe cute (new HibernateCallback (){
Public Object doInHibernate (Session session)
Throws HibernateException, SQLException {
Query query = session. createQuery (hql );
Int row#query.exe cuteUpdate ();
Return row;
}
});
Return row;
}
Public int exeupdatehql (final String hql, final String [] prams ){
Int row = 0;
Row#(integer%gethibernatetemplate(cmd.exe cute (new HibernateCallback (){
Public Object doInHibernate (Session session)
Throws HibernateException, SQLException {
Query query = session. createQuery (hql );
If (prams! = Null ){
For (int I = 0; I & lt; prams. length; I ++ ){
Query. setString (I, prams [I]);
}
}
Int row#query.exe cuteUpdate ();
Return row;
}
});
Return row;
}
/* Paging method. The pagesize parameter indicates the data volume displayed on each page. startpage indicates that the database reads data from the specified start to the specified location,
* Example: int startpage = (current page-1) * pagesize;
* The current page number is 1, The pagesize is 3, and the data between 0 and 2 in the database is read.
* The current page number is 2, The pagesize is 3, and 3 to 5 data are read from the database.
**/
Public List pageList (final String hql, final int pagesize, final int startpage ){
Return gethibernatetemplate(cmd.exe cuteFind (new HibernateCallback (){
Public Object doInHibernate (Session session)
Throws HibernateException, SQLException {
Query query = session. createQuery (hql );
Query. setFirstResult (startpage );
Query. setMaxResults (pagesize );
List list = query. list ();
Return list;
}
});
}
Public List pageList (final String hql, final int pagesize, final int startpage, final String [] parms ){
Return gethibernatetemplate(cmd.exe cuteFind (new HibernateCallback (){
Public Object doInHibernate (Session session)
Throws HibernateException, SQLException {
Query query = session. createQuery (hql );
If (parms! = Null ){
For (int I = 0; I & lt; parms. length; I ++ ){
Query. setString (I, parms [I]);
}
}
Query. setFirstResult (startpage );
Query. setMaxResults (pagesize );
List list = query. list ();
Return list;
}
});
}
}
Paging code example:
// The current page, the data size displayed in pagesize
Public List & lt; LinkMan> pagenumber (int page, int pagesize, LinkMan linkman ){
System. out. println (page + "_" + pagesize );
List <LinkMan> list = null;
String where = "where 1 = 1 ";
If (linkman! = Null ){
If (! "". Equals (linkman. getName ())){
Where = where + "and l. surName | l. name like '%" + linkman. getSurName () + "% '";
}
If (! "". Equals (linkman. getCustomerName ())){
Where = where + "and l. CustomerName like '%" + linkman. getCustomerName () + "% '";
}
If (! "". Equals (linkman. getEmail ())){
Where = where + "and l. Email like '%" + linkman. getEmail () + "% '";
}
}
String hql = "from LinkMan l" + where + "order by l. linkManID desc ";
Int startpage = (page-1) * pagesize;
List = super. pageList (hql, pagesize, startpage );
Return list;
}
// Count the number of queried data entries Based on the query Condition
Public int getsearchcount (LinkMan linkman ){
Int count = 0;
String where = "where 1 = 1 ";
If (linkman! = Null ){
If (! "". Equals (linkman. getName ())){
Where = where + "and l. surName | l. name like '%" + linkman. getSurName () + "% '";
}
If (! "". Equals (linkman. getCustomerName ())){
Where = where + "and l. CustomerName like '%" + linkman. getCustomerName () + "% '";
}
If (! "". Equals (linkman. getEmail ())){
Where = where + "and l. Email like '%" + linkman. getEmail () + "% '";
}
}
String hql = "select count (*) from LinkMan l" + where;
Count = Integer. valueOf (super. getuniqbyhql (hql). toString ());
Return count;
}
Page number of a paging action
Public String dolist (){
List <LinkMan> list = lService. getAllLinkMan ();
Int listcount = list. size ();
Page pagenum = new Page ();
Pagenum. setRspagecount (listcount); // The total number of data entries.
Pagenum. setUppage (1); // Previous Page
Pagenum. setNextpage (1); // next page
Pagenum. setPagesize (3); // number of entries displayed on the page
Pagenum. setPagecount (pagenum. getRspagecount () + pagenum. getPagesize ()-1)/pagenum. getPagesize (); // the total number of pages
Pagenum. setPage (1); // current page number
String pagestr = ServletActionContext. getRequest (). getParameter ("page ");
If (null = pagestr ){
Pagenum. setPage (1 );
}
Try {
Pagenum. setPage (Integer. valueOf (pagestr ));
} Catch (Exception e ){
Pagenum. setPage (1 );
}
If (pagenum. getPage () <= 0 ){
Pagenum. setPage (1 );
}
If (pagenum. getPage ()> pagenum. getPagecount ()){
Pagenum. setPage (pagenum. getPagecount ());
}
If (pagenum. getPage ()-1 & gt; 0 ){
Pagenum. setUppage (pagenum. getPage ()-1 );
} Else {
Pagenum. setUppage (0 );
}
If (pagenum. getPage () + 1 & gt; pagenum. getPagecount ()){
Pagenum. setNextpage (0 );
} Else {
Pagenum. setNextpage (pagenum. getPage () + 1 );
}
List <LinkMan> listpage = lService. getpagenumber (pagenum. getPage (), pagenum. getPagesize (), null );
Request. put ("list", listpage );
Request. put ("pagenum", pagenum );
Return SUCCESS;
}
This article is from the "Youth bag" blog

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.