mybatis3.2.8 与 hibernate4.3.6 混用

简介: mybatis、hibernate这二个框架各有特色,对于复杂的查询,利用mybatis直接手写sql控制起来更灵活,而一般的insert/update,hibernate比较方便。同一个项目中,这二个框架可以和谐共存,下面是一些步骤: 一、版本要求 Spring 4.11 + hibernate 4.3.6 + mybatis 3.2.8 + struts 2.3.16.3 (这是目前各框架的最新版本) 建议:如果用hibernate 4.x ,Spring最好也是4.x系列,否则getCurrentSession()容易报错。

mybatis、hibernate这二个框架各有特色,对于复杂的查询,利用mybatis直接手写sql控制起来更灵活,而一般的insert/update,hibernate比较方便。同一个项目中,这二个框架可以和谐共存,下面是一些步骤:

一、版本要求

Spring 4.11 + hibernate 4.3.6 + mybatis 3.2.8 + struts 2.3.16.3 (这是目前各框架的最新版本)

建议:如果用hibernate 4.x ,Spring最好也是4.x系列,否则getCurrentSession()容易报错。

二、pom.xml依赖项

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  4     <modelVersion>4.0.0</modelVersion>
  5     <groupId>infosky</groupId>
  6     <artifactId>struts2-rest-ex</artifactId>
  7     <packaging>war</packaging>
  8     <version>1.0</version>
  9     <properties>
 10         <java-version>1.6</java-version>
 11         <struts2.version>2.3.16.3</struts2.version>
 12         <spring.version>4.1.1.RELEASE</spring.version>
 13         <mybatis.version>3.2.8</mybatis.version>
 14         <hibernate.version>4.3.6.Final</hibernate.version>
 15     </properties>
 16     <dependencies>
 17 
 18         <dependency>
 19             <groupId>commons-dbcp</groupId>
 20             <artifactId>commons-dbcp</artifactId>
 21             <version>1.4</version>
 22         </dependency>
 23 
 24         <!-- oracle -->
 25         <dependency>
 26             <groupId>com.oracle</groupId>
 27             <artifactId>ojdbc6</artifactId>
 28             <version>11.2.0.3</version>
 29         </dependency>
 30 
 31         <dependency>
 32             <groupId>asm</groupId>
 33             <artifactId>asm</artifactId>
 34             <version>3.3.1</version>
 35         </dependency>
 36 
 37         <dependency>
 38             <groupId>asm</groupId>
 39             <artifactId>asm-commons</artifactId>
 40             <version>3.3.1</version>
 41         </dependency>
 42 
 43         <dependency>
 44             <groupId>asm</groupId>
 45             <artifactId>asm-tree</artifactId>
 46             <version>3.3.1</version>
 47         </dependency>
 48 
 49         <dependency>
 50             <groupId>commons-beanutils</groupId>
 51             <artifactId>commons-beanutils</artifactId>
 52             <version>1.8.3</version>
 53         </dependency>
 54 
 55         <dependency>
 56             <groupId>commons-collections</groupId>
 57             <artifactId>commons-collections</artifactId>
 58             <version>3.2.1</version>
 59         </dependency>
 60 
 61         <dependency>
 62             <groupId>commons-fileupload</groupId>
 63             <artifactId>commons-fileupload</artifactId>
 64             <version>1.3</version>
 65         </dependency>
 66 
 67         <dependency>
 68             <groupId>commons-io</groupId>
 69             <artifactId>commons-io</artifactId>
 70             <version>2.2</version>
 71         </dependency>
 72 
 73         <dependency>
 74             <groupId>org.apache.commons</groupId>
 75             <artifactId>commons-lang3</artifactId>
 76             <version>3.1</version>
 77         </dependency>
 78 
 79         <dependency>
 80             <groupId>javassist</groupId>
 81             <artifactId>javassist</artifactId>
 82             <version>3.12.1.GA</version>
 83         </dependency>
 84 
 85         <dependency>
 86             <groupId>ognl</groupId>
 87             <artifactId>ognl</artifactId>
 88             <version>3.0.6</version>
 89         </dependency>
 90 
 91 
 92         <!-- log -->
 93         <dependency>
 94             <groupId>org.apache.logging.log4j</groupId>
 95             <artifactId>log4j-api</artifactId>
 96             <version>2.0.2</version>
 97         </dependency>
 98         <dependency>
 99             <groupId>org.apache.logging.log4j</groupId>
100             <artifactId>log4j-core</artifactId>
101             <version>2.0.2</version>
102         </dependency>
103         <dependency>
104             <groupId>org.apache.logging.log4j</groupId>
105             <artifactId>log4j-web</artifactId>
106             <version>2.0.2</version>
107         </dependency>
108         <dependency>
109             <groupId>org.slf4j</groupId>
110             <artifactId>slf4j-api</artifactId>
111             <version>1.7.7</version>
112         </dependency>
113 
114         <dependency>
115             <groupId>net.sf.ezmorph</groupId>
116             <artifactId>ezmorph</artifactId>
117             <version>1.0.6</version>
118         </dependency>
119 
120         <dependency>
121             <groupId>org.freemarker</groupId>
122             <artifactId>freemarker</artifactId>
123             <version>2.3.19</version>
124         </dependency>
125 
126         <dependency>
127             <groupId>org.codehaus.jackson</groupId>
128             <artifactId>jackson-core-asl</artifactId>
129             <version>1.9.10</version>
130         </dependency>
131 
132         <dependency>
133             <groupId>org.codehaus.jackson</groupId>
134             <artifactId>jackson-mapper-asl</artifactId>
135             <version>1.9.10</version>
136         </dependency>
137 
138         <dependency>
139             <groupId>net.sf.json-lib</groupId>
140             <artifactId>json-lib</artifactId>
141             <version>2.4</version>
142             <classifier>jdk15</classifier>
143         </dependency>
144 
145         <dependency>
146             <groupId>org.apache.struts</groupId>
147             <artifactId>struts2-convention-plugin</artifactId>
148             <version>2.3.16</version>
149         </dependency>
150 
151         <dependency>
152             <groupId>org.apache.struts</groupId>
153             <artifactId>struts2-config-browser-plugin</artifactId>
154             <version>2.3.16</version>
155         </dependency>
156 
157         <dependency>
158             <groupId>org.apache.struts</groupId>
159             <artifactId>struts2-core</artifactId>
160             <version>${struts2.version}</version>
161         </dependency>
162 
163         <dependency>
164             <groupId>org.apache.struts</groupId>
165             <artifactId>struts2-rest-plugin</artifactId>
166             <version>2.3.16</version>
167         </dependency>
168 
169         <dependency>
170             <groupId>com.thoughtworks.xstream</groupId>
171             <artifactId>xstream</artifactId>
172             <version>1.4.3</version>
173         </dependency>
174 
175         <dependency>
176             <groupId>org.apache.struts.xwork</groupId>
177             <artifactId>xwork-core</artifactId>
178             <version>${struts2.version}</version>
179         </dependency>
180 
181         <!-- Servlet -->
182         <dependency>
183             <groupId>javax.servlet</groupId>
184             <artifactId>servlet-api</artifactId>
185             <version>2.5</version>
186             <scope>provided</scope>
187         </dependency>
188 
189         <!-- spring -->
190         <dependency>
191             <groupId>org.apache.struts</groupId>
192             <artifactId>struts2-spring-plugin</artifactId>
193             <version>${struts2.version}</version>
194         </dependency>
195 
196         <dependency>
197             <groupId>org.springframework</groupId>
198             <artifactId>spring-context</artifactId>
199             <version>${spring.version}</version>
200         </dependency>
201 
202         <dependency>
203             <groupId>org.springframework</groupId>
204             <artifactId>spring-orm</artifactId>
205             <version>${spring.version}</version>
206         </dependency>
207 
208         <dependency>
209             <groupId>org.springframework</groupId>
210             <artifactId>spring-beans</artifactId>
211             <version>${spring.version}</version>
212         </dependency>
213 
214         <dependency>
215             <groupId>org.springframework</groupId>
216             <artifactId>spring-core</artifactId>
217             <version>${spring.version}</version>
218         </dependency>
219 
220         <dependency>
221             <groupId>org.springframework</groupId>
222             <artifactId>spring-web</artifactId>
223             <version>${spring.version}</version>
224         </dependency>
225 
226         <dependency>
227             <groupId>org.springframework</groupId>
228             <artifactId>spring-context</artifactId>
229             <version>${spring.version}</version>
230         </dependency>
231 
232         <dependency>
233             <groupId>org.springframework</groupId>
234             <artifactId>spring-context-support</artifactId>
235             <version>${spring.version}</version>
236         </dependency>
237 
238         <dependency>
239             <groupId>org.springframework</groupId>
240             <artifactId>spring-expression</artifactId>
241             <version>${spring.version}</version>
242         </dependency>
243 
244         <dependency>
245             <groupId>org.springframework</groupId>
246             <artifactId>spring-jdbc</artifactId>
247             <version>${spring.version}</version>
248         </dependency>
249 
250         <dependency>
251             <groupId>org.springframework</groupId>
252             <artifactId>spring-tx</artifactId>
253             <version>${spring.version}</version>
254         </dependency>
255 
256         <dependency>
257             <groupId>org.springframework</groupId>
258             <artifactId>spring-aop</artifactId>
259             <version>${spring.version}</version>
260         </dependency>
261 
262 
263         <dependency>
264             <groupId>org.aspectj</groupId>
265             <artifactId>aspectjweaver</artifactId>
266             <version>1.7.3</version>
267         </dependency>
268 
269         <dependency>
270             <groupId>aopalliance</groupId>
271             <artifactId>aopalliance</artifactId>
272             <version>1.0</version>
273         </dependency>
274 
275 
276         <dependency>
277             <groupId>junit</groupId>
278             <artifactId>junit</artifactId>
279             <version>4.11</version>
280         </dependency>
281 
282         <!-- mybatis -->
283         <dependency>
284             <groupId>org.mybatis</groupId>
285             <artifactId>mybatis-spring</artifactId>
286             <version>1.2.2</version>
287         </dependency>
288 
289         <dependency>
290             <groupId>org.mybatis</groupId>
291             <artifactId>mybatis</artifactId>
292             <version>${mybatis.version}</version>
293         </dependency>
294 
295         <dependency>
296             <groupId>com.github.miemiedev</groupId>
297             <artifactId>mybatis-paginator</artifactId>
298             <version>1.2.15</version>
299         </dependency>
300 
301         <!-- hibernate -->
302         <dependency>
303             <groupId>org.hibernate</groupId>
304             <artifactId>hibernate-core</artifactId>
305             <version>${hibernate.version}</version>
306         </dependency>
307 
308         <dependency>
309             <groupId>xml-apis</groupId>
310             <artifactId>xml-apis</artifactId>
311             <version>1.0.b2</version>
312             <scope>provided</scope>
313         </dependency>
314 
315 
316     </dependencies>
317 
318     <profiles>
319         <profile>
320             <!-- 开发环境 -->
321             <id>dev</id>
322             <properties>
323                 <db-url>jdbc:oracle:thin:@172.21.129.51:1521:orcl</db-url>
324                 <db-username>***</db-username>
325                 <db-password>***</db-password>
326             </properties>
327             <!-- 默认激活本环境 -->
328             <activation>
329                 <activeByDefault>true</activeByDefault>
330             </activation>
331         </profile>
332         <profile>
333             <!-- 测试环境 -->
334             <id>test</id>
335             <properties>
336                 <db-url>jdbc:oracle:thin:@172.21.129.51:1521:orcl</db-url>
337                 <db-username>***</db-username>
338                 <db-password>***</db-password>
339             </properties>
340         </profile>
341     </profiles>
342 
343     <build>
344         <finalName>struts2-rest-ex</finalName>
345         <resources>
346             <resource>
347                 <directory>src/main/resources</directory>
348                 <filtering>true</filtering>
349             </resource>
350         </resources>
351         <plugins>
352             <plugin>
353                 <groupId>org.apache.maven.plugins</groupId>
354                 <artifactId>maven-compiler-plugin</artifactId>
355                 <version>2.5.1</version>
356                 <configuration>
357                     <source>1.6</source>
358                     <target>1.6</target>
359                     <encoding>utf-8</encoding>
360                 </configuration>
361             </plugin>
362 
363             <plugin>
364                 <artifactId>maven-source-plugin</artifactId>
365                 <version>2.1.2</version>
366                 <executions>
367                     <execution>
368                         <phase>package</phase>
369                         <goals>
370                             <goal>jar-no-fork</goal>
371                         </goals>
372                     </execution>
373                 </executions>
374             </plugin>
375 
376             <plugin>
377                 <groupId>org.apache.maven.plugins</groupId>
378                 <artifactId>maven-surefire-plugin</artifactId>
379                 <version>2.16</version>
380                 <configuration>
381                     <forkMode>once</forkMode>
382                     <argLine>-Dfile.encoding=UTF-8</argLine>
383                 </configuration>
384             </plugin>
385         </plugins>
386     </build>
387     <organization>
388         <name>yjmyzz</name>
389         <url>http://yjmyzz.cnblogs.com/</url>
390     </organization>
391 
392 </project>
View Code

最终打包后,WEB-INF/lib下的jar文件列表为:

antlr-2.7.7.jar
aopalliance-1.0.jar
asm-3.3.1.jar
asm-commons-3.3.1.jar
asm-tree-3.3.1.jar
aspectjweaver-1.7.3.jar
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-dbcp-1.4.jar
commons-fileupload-1.3.jar
commons-io-2.2.jar
commons-lang-2.3.jar
commons-lang3-3.1.jar
commons-logging-1.1.1.jar
commons-pool-1.5.4.jar
dom4j-1.6.1.jar
ezmorph-1.0.6.jar
freemarker-2.3.19.jar
hamcrest-core-1.3.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jackson-core-asl-1.9.10.jar
jackson-mapper-asl-1.9.10.jar
jandex-1.1.0.Final.jar
javassist-3.12.1.GA.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
json-lib-2.4-jdk15.jar
junit-4.11.jar
log4j-api-2.0.2.jar
log4j-core-2.0.2.jar
log4j-web-2.0.2.jar
mybatis-3.2.8.jar
mybatis-paginator-1.2.15.jar
mybatis-spring-1.2.2.jar
ognl-3.0.6.jar
ojdbc6-11.2.0.3.jar
slf4j-api-1.7.7.jar
spring-aop-4.1.1.RELEASE.jar
spring-beans-4.1.1.RELEASE.jar
spring-context-4.1.1.RELEASE.jar
spring-context-support-4.1.1.RELEASE.jar
spring-core-4.1.1.RELEASE.jar
spring-expression-4.1.1.RELEASE.jar
spring-jdbc-4.1.1.RELEASE.jar
spring-orm-4.1.1.RELEASE.jar
spring-tx-4.1.1.RELEASE.jar
spring-web-4.1.1.RELEASE.jar
struts2-config-browser-plugin-2.3.16.jar
struts2-convention-plugin-2.3.16.jar
struts2-core-2.3.16.3.jar
struts2-rest-plugin-2.3.16.jar
struts2-spring-plugin-2.3.16.3.jar
xmlpull-1.1.3.1.jar
xpp3_min-1.1.4c.jar
xstream-1.4.3.jar
xwork-core-2.3.16.3.jar

三、Spring配置(关键)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 4     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xsi:schemaLocation="
 7      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
 8      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 9      http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
10      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
11      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
12     default-autowire="byName">
13 
14     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
15         destroy-method="close">
16         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
17         <property name="url" value="jdbc:oracle:thin:@172.21.129.**:1521:orcl" />
18         <property name="username" value="***" />
19         <property name="password" value="***" />
20         <property name="defaultAutoCommit" value="false" />
21         <property name="initialSize" value="2" />
22         <property name="maxActive" value="10" />
23         <property name="maxWait" value="60000" />
24     </bean>
25 
26     <bean id="sessionFactory"
27         class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
28         <property name="dataSource" ref="dataSource" />
29         <property name="packagesToScan">
30             <list>
31                 <value>com.cnblogs.yjmyzz.entity</value>
32             </list>
33         </property>
34         <property name="mappingLocations">
35             <list>
36                 <value>classpath*:hibernate/**/*.hbm.xml</value>
37             </list>
38         </property>
39         <property name="hibernateProperties">
40             <props>
41                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
42                 <!-- <prop key="current_session_context_class">thread</prop> -->
43                 <prop key="hibernate.format_sql">false</prop>
44                 <prop key="hibernate.show_sql">true</prop>
45                 <prop key="hibernate.use_sql_comments">true</prop>
46                 <prop key="hibernate.max_fetch_depth">3</prop>
47                 <prop key="hibernate.jdbc.batch_size">20</prop>
48                 <prop key="hibernate.jdbc.fetch_size">20</prop>
49                 <prop key="hibernate.cache.use_second_level_cache">false</prop>
50             </props>
51         </property>
52     </bean>
53 
54     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
55         <property name="dataSource" ref="dataSource" />
56         <property name="configLocation" value="classpath:mybatis-config.xml"></property>
57         <property name="typeAliasesPackage" value="com.cnblogs.yjmyzz.entity"></property>
58         <property name="mapperLocations" value="classpath:mybatis/**/*.xml"></property>
59         <property name="plugins">
60             <list>
61                 <bean
62                     class="com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor">
63                     <property name="dialectClass"
64                         value="com.github.miemiedev.mybatis.paginator.dialect.OracleDialect"></property>
65                 </bean>
66             </list>
67         </property>
68     </bean>
69 
70     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
71         <property name="basePackage" value="com.cnblogs.yjmyzz.mybatis.mapper" />
72     </bean>
73 
74     <bean id="transactionManager"
75         class="org.springframework.orm.hibernate4.HibernateTransactionManager">
76         <property name="sessionFactory">
77             <ref local="sessionFactory" />
78         </property>
79     </bean>
80 
81     <tx:advice id="txAdvice" transaction-manager="transactionManager">
82         <tx:attributes>
83             <tx:method name="do*" read-only="false" rollback-for="java.lang.Exception" />
84             <tx:method name="*" propagation="SUPPORTS" read-only="true" />
85         </tx:attributes>
86     </tx:advice>
87 
88     <aop:config>
89         <aop:pointcut id="pc"
90             expression="execution(* com.cnblogs.yjmyzz.service.*.*(..))" />
91         <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
92     </aop:config>
93 
94 </beans>
View Code

有几个关键点:

a) mybatis与hibernate的sessionFactory,共用同一个dataSource

b) 事务管理共用hibernate的事务管理

四、web.xml配置 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 5 
 6     <display-name>struts2-app-sample</display-name>
 7 
 8     <listener>
 9         <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
10     </listener>
11     <filter>
12         <filter-name>log4jServletFilter</filter-name>
13         <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
14     </filter>
15     <filter-mapping>
16         <filter-name>log4jServletFilter</filter-name>
17         <url-pattern>/*</url-pattern>
18         <dispatcher>REQUEST</dispatcher>
19         <dispatcher>FORWARD</dispatcher>
20         <dispatcher>INCLUDE</dispatcher>
21         <dispatcher>ERROR</dispatcher>
22     </filter-mapping>
23 
24     <context-param>
25         <param-name>contextConfigLocation</param-name>
26         <param-value>classpath:spring.xml</param-value>
27     </context-param>
28     <listener>
29         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
30     </listener>
31 
32     <filter>
33         <filter-name>struts2</filter-name>
34         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
35         <init-param>
36             <param-name>loggerFactory</param-name>
37             <param-value>com.opensymphony.xwork2.util.logging.slf4j.Slf4jLoggerFactory</param-value>
38         </init-param>
39     </filter>
40 
41     <filter>
42         <filter-name>openSessionInViewFilter</filter-name>
43         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
44         <init-param>
45             <param-name>singleSession</param-name>
46             <param-value>true</param-value>
47         </init-param>
48     </filter>
49 
50     <filter-mapping>
51         <filter-name>struts2</filter-name>
52         <url-pattern>/*</url-pattern>
53     </filter-mapping>
54 
55     <welcome-file-list>
56         <welcome-file>index.html</welcome-file>
57     </welcome-file-list>
58 
59 </web-app>
View Code

五、代码调用

5.1 服务层基类

 1 package com.cnblogs.yjmyzz.service.support;
 2 
 3 import java.io.Serializable;
 4 
 5 import javax.annotation.Resource;
 6 
 7 import org.apache.ibatis.session.SqlSessionFactory;
 8 import org.hibernate.Session;
 9 import org.hibernate.SessionFactory;
10 import org.hibernate.StatelessSession;
11 
12 public class BaseServiceImpl implements Serializable {
13 
14     private static final long serialVersionUID = -33988360094493502L;
15 
16     /**
17      * hibernate入口
18      */
19     @Resource(name = "sessionFactory")
20     protected SessionFactory hibernateSessionFactory;
21 
22     /**
23      * mybatis入口
24      */
25     @Resource(name = "sqlSessionFactory")
26     protected SqlSessionFactory mybatisSessionFactory;
27 
28     protected Session openSession() {
29         return hibernateSessionFactory.openSession();
30     }
31 
32     protected StatelessSession openStatelessSession() {
33         return hibernateSessionFactory.openStatelessSession();
34     }
35 
36     protected Session getCurrentSession() {
37         return hibernateSessionFactory.getCurrentSession();
38     }
39 
40 }
View Code

其它各业务服务实现类,都继承自它。当然,也可以弄一个BaseDAO,对hibernate做些封装

  1 package com.cnblogs.yjmyzz.dao;
  2 
  3 import java.io.Serializable;
  4 import java.util.List;
  5 
  6 /**
  7  * 基础数据库操作类
  8  * 
  9  * @author ss
 10  * 
 11  */
 12 public interface BaseDAO<T> {
 13 
 14     /**
 15      * 保存一个对象
 16      * 
 17      * @param o
 18      * @return
 19      */
 20     public Serializable save(T o);
 21 
 22     /**
 23      * 删除一个对象
 24      * 
 25      * @param o
 26      */
 27     public void delete(T o);
 28 
 29     /**
 30      * 更新一个对象
 31      * 
 32      * @param o
 33      */
 34     public void update(T o);
 35 
 36     /**
 37      * 保存或更新对象
 38      * 
 39      * @param o
 40      */
 41     public void saveOrUpdate(T o);
 42 
 43     /**
 44      * 查询
 45      * 
 46      * @param hql
 47      * @return
 48      */
 49     public List<T> find(String hql);
 50 
 51     /**
 52      * 查询集合
 53      * 
 54      * @param hql
 55      * @param param
 56      * @return
 57      */
 58     public List<T> find(String hql, Object[] param);
 59 
 60     /**
 61      * 查询集合
 62      * 
 63      * @param hql
 64      * @param param
 65      * @return
 66      */
 67     public List<T> find(String hql, List<Object> param);
 68 
 69     /**
 70      * 查询集合(带分页)
 71      * 
 72      * @param hql
 73      * @param param
 74      * @param page
 75      *            查询第几页
 76      * @param rows
 77      *            每页显示几条记录
 78      * @return
 79      */
 80     public List<T> find(String hql, Object[] param, Integer page, Integer rows);
 81 
 82     /**
 83      * 查询集合(带分页)
 84      * 
 85      * @param hql
 86      * @param param
 87      * @param page
 88      * @param rows
 89      * @return
 90      */
 91     public List<T> find(String hql, List<Object> param, Integer page,
 92             Integer rows);
 93 
 94     /**
 95      * 获得一个对象
 96      * 
 97      * @param c
 98      *            对象类型
 99      * @param id
100      * @return Object
101      */
102     public T get(Class<T> c, Serializable id);
103 
104     /**
105      * 获得一个对象
106      * 
107      * @param hql
108      * @param param
109      * @return Object
110      */
111     public T get(String hql, Object[] param);
112 
113     /**
114      * 获得一个对象
115      * 
116      * @param hql
117      * @param param
118      * @return
119      */
120     public T get(String hql, List<Object> param);
121 
122     /**
123      * select count(*) from 类
124      * 
125      * @param hql
126      * @return
127      */
128     public Long count(String hql);
129 
130     /**
131      * select count(*) from 类
132      * 
133      * @param hql
134      * @param param
135      * @return
136      */
137     public Long count(String hql, Object[] param);
138 
139     /**
140      * select count(*) from 类
141      * 
142      * @param hql
143      * @param param
144      * @return
145      */
146     public Long count(String hql, List<Object> param);
147 
148     /**
149      * 执行HQL语句
150      * 
151      * @param hql
152      * @return 响应数目
153      */
154     public Integer executeHql(String hql);
155 
156     /**
157      * 执行HQL语句
158      * 
159      * @param hql
160      * @param param
161      * @return 响应数目
162      */
163     public Integer executeHql(String hql, Object[] param);
164 
165     /**
166      * 执行HQL语句
167      * 
168      * @param hql
169      * @param param
170      * @return
171      */
172     public Integer executeHql(String hql, List<Object> param);
173 
174 }
View Code
  1 package com.cnblogs.yjmyzz.dao.impl;
  2 
  3 import com.cnblogs.yjmyzz.dao.BaseDAO;
  4 
  5 import java.io.Serializable;
  6 import java.util.List;
  7 
  8 import org.hibernate.Query;
  9 import org.hibernate.Session;
 10 import org.hibernate.SessionFactory;
 11 import org.springframework.beans.factory.annotation.Autowired;
 12 import org.springframework.stereotype.Component;
 13 import org.springframework.stereotype.Repository;
 14 
 15 @Component("baseDAO")
 16 @SuppressWarnings("all")
 17 public class BaseDAOImpl<T> implements BaseDAO<T> {
 18 
 19     private SessionFactory sessionFactory;
 20 
 21     public SessionFactory getSessionFactory() {
 22         return sessionFactory;
 23     }
 24 
 25     @Autowired
 26     public void setSessionFactory(SessionFactory sessionFactory) {
 27         this.sessionFactory = sessionFactory;
 28     }
 29 
 30     private Session getCurrentSession() {
 31         return sessionFactory.getCurrentSession();
 32     }
 33 
 34     public Serializable save(T o) {
 35         return this.getCurrentSession().save(o);
 36     }
 37 
 38     public void delete(T o) {
 39         this.getCurrentSession().delete(o);
 40     }
 41 
 42     public void update(T o) {
 43         this.getCurrentSession().update(o);
 44     }
 45 
 46     public void saveOrUpdate(T o) {
 47         this.getCurrentSession().saveOrUpdate(o);
 48     }
 49 
 50     public List<T> find(String hql) {
 51         return this.getCurrentSession().createQuery(hql).list();
 52     }
 53 
 54     public List<T> find(String hql, Object[] param) {
 55         Query q = this.getCurrentSession().createQuery(hql);
 56         if (param != null && param.length > 0) {
 57             for (int i = 0; i < param.length; i++) {
 58                 q.setParameter(i, param[i]);
 59             }
 60         }
 61         return q.list();
 62     }
 63 
 64     public List<T> find(String hql, List<Object> param) {
 65         Query q = this.getCurrentSession().createQuery(hql);
 66         if (param != null && param.size() > 0) {
 67             for (int i = 0; i < param.size(); i++) {
 68                 q.setParameter(i, param.get(i));
 69             }
 70         }
 71         return q.list();
 72     }
 73 
 74     public List<T> find(String hql, Object[] param, Integer page, Integer rows) {
 75         if (page == null || page < 1) {
 76             page = 1;
 77         }
 78         if (rows == null || rows < 1) {
 79             rows = 10;
 80         }
 81         Query q = this.getCurrentSession().createQuery(hql);
 82         if (param != null && param.length > 0) {
 83             for (int i = 0; i < param.length; i++) {
 84                 q.setParameter(i, param[i]);
 85             }
 86         }
 87         return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
 88     }
 89 
 90     public List<T> find(String hql, List<Object> param, Integer page,
 91             Integer rows) {
 92         if (page == null || page < 1) {
 93             page = 1;
 94         }
 95         if (rows == null || rows < 1) {
 96             rows = 10;
 97         }
 98         Query q = this.getCurrentSession().createQuery(hql);
 99         if (param != null && param.size() > 0) {
100             for (int i = 0; i < param.size(); i++) {
101                 q.setParameter(i, param.get(i));
102             }
103         }
104         return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
105     }
106 
107     public T get(Class<T> c, Serializable id) {
108         return (T) this.getCurrentSession().get(c, id);
109     }
110 
111     public T get(String hql, Object[] param) {
112         List<T> l = this.find(hql, param);
113         if (l != null && l.size() > 0) {
114             return l.get(0);
115         } else {
116             return null;
117         }
118     }
119 
120     public T get(String hql, List<Object> param) {
121         List<T> l = this.find(hql, param);
122         if (l != null && l.size() > 0) {
123             return l.get(0);
124         } else {
125             return null;
126         }
127     }
128 
129     public Long count(String hql) {
130         return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
131     }
132 
133     public Long count(String hql, Object[] param) {
134         Query q = this.getCurrentSession().createQuery(hql);
135         if (param != null && param.length > 0) {
136             for (int i = 0; i < param.length; i++) {
137                 q.setParameter(i, param[i]);
138             }
139         }
140         return (Long) q.uniqueResult();
141     }
142 
143     public Long count(String hql, List<Object> param) {
144         Query q = this.getCurrentSession().createQuery(hql);
145         if (param != null && param.size() > 0) {
146             for (int i = 0; i < param.size(); i++) {
147                 q.setParameter(i, param.get(i));
148             }
149         }
150         return (Long) q.uniqueResult();
151     }
152 
153     public Integer executeHql(String hql) {
154         return this.getCurrentSession().createQuery(hql).executeUpdate();
155     }
156 
157     public Integer executeHql(String hql, Object[] param) {
158         Query q = this.getCurrentSession().createQuery(hql);
159         if (param != null && param.length > 0) {
160             for (int i = 0; i < param.length; i++) {
161                 q.setParameter(i, param[i]);
162             }
163         }
164         return q.executeUpdate();
165     }
166 
167     public Integer executeHql(String hql, List<Object> param) {
168         Query q = this.getCurrentSession().createQuery(hql);
169         if (param != null && param.size() > 0) {
170             for (int i = 0; i < param.size(); i++) {
171                 q.setParameter(i, param.get(i));
172             }
173         }
174         return q.executeUpdate();
175     }
176 
177 }
View Code

至于mybatis,就没必要封装了,因为各xxxMapper接口,注入后可以直接拿来调

5.2 调用示例

 1 package com.cnblogs.yjmyzz.service.support;
 2 
 3 import java.math.BigDecimal;
 4 import java.util.*;
 5 
 6 import javax.annotation.Resource;
 7 
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.stereotype.Service;
10 
11 import com.cnblogs.yjmyzz.convertor.OrderConverter;
12 import com.cnblogs.yjmyzz.dao.BaseDAO;
13 import com.cnblogs.yjmyzz.dto.Order;
14 import com.cnblogs.yjmyzz.entity.TOrder;
15 import com.cnblogs.yjmyzz.mybatis.mapper.OrderMapper;
16 import com.cnblogs.yjmyzz.service.OrderService;
17 
18 @Service
19 public class OrdersServiceImpl extends BaseServiceImpl implements OrderService {
20 
21     @Autowired
22     OrderMapper orderMapper;
23 
24     @Resource
25     BaseDAO<TOrder> tOrderDAO;
26 
27     private static final long serialVersionUID = 1513133416493770048L;
28 
29     @Override
30     public Order get(String id) {
31         // hibernate实现
32         // return OrderConverter.toDto((TOrder) getCurrentSession().get(
33         // TOrder.class, new BigDecimal(Integer.parseInt(id))));
34         return OrderConverter.toDto(tOrderDAO.get(TOrder.class, new BigDecimal(
35                 Integer.parseInt(id))));
36 
37         // mybatis实现
38         // return
39         // OrderConverter.toDto(orderMapper.getOrder(Integer.parseInt(id)));
40     }
41 
42     @Override
43     public List<Order> getAll() {
44         List<TOrder> entities = orderMapper.getAllOrder();
45         List<Order> orders = new ArrayList<Order>();
46         for (TOrder entity : entities) {
47             orders.add(OrderConverter.toDto(entity));
48         }
49         return orders;
50     }
51 
52     @Override
53     public void doSave(Order order) {
54         // hibernate
55         TOrder entity = OrderConverter.toEntity(order);
56         if (entity.getId() != null) {
57             entity = (TOrder) getCurrentSession().get(TOrder.class,
58                     entity.getId());
59 
60             // update fields
61             entity.setClientname(order.getClientName());
62             entity.setAmount(new BigDecimal(order.getAmount()));
63         }
64         getCurrentSession().saveOrUpdate(entity);
65     }
66 
67     @Override
68     public void doRemove(String id) {
69         // mybatis
70         orderMapper.deleteOrder(Integer.parseInt(id));
71 
72     }
73 
74 }
View Code

其它注意事项:

hibernate 4.x以后,entity类上的注解,最好改成@Entity("TABLE_NAME"),而非以前的@Table(xxx),参考:

@Entity(name = "T_ORDER")
public class TOrder implements java.io.Serializable {
View Code

示例代码下载:struts-hibernate-mybatis-rest.zip 

目录
相关文章
|
6月前
|
SQL Java 数据库连接
hibernate和mybatis的区别
hibernate和mybatis的区别
|
SQL XML Java
mybatis基本构成&mybatis与hibernate的区别&添加mybatis支持
mybatis基本构成&mybatis与hibernate的区别&添加mybatis支持
|
3月前
|
SQL Java 数据库连接
MyBatis 和 Hibernate 有什么区别?
【8月更文挑战第21天】
64 0
|
4月前
|
SQL Java 数据库连接
Java面试题:简述ORM框架(如Hibernate、MyBatis)的工作原理及其优缺点。
Java面试题:简述ORM框架(如Hibernate、MyBatis)的工作原理及其优缺点。
70 0
|
6月前
|
SQL Java 数据库连接
MyBatis与Hibernate区别
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
|
6月前
|
SQL 存储 Java
MyBatis与Hibernate有什么区别?
MyBatis与Hibernate有什么区别?
42 1
|
11月前
|
SQL 缓存 Java
聊聊Hibernate和Mybatis的区别
聊聊Hibernate和Mybatis的区别
53 0
|
SQL Java 数据库连接
Java 最常见的面试题:mybatis 和 hibernate 的区别有哪些?
Java 最常见的面试题:mybatis 和 hibernate 的区别有哪些?
147 0
|
SQL 缓存 Java
Mybatis和hibernate到底有什么异同?
本文在这里给大家科普一下 MyBatis 和 Hibernate,看它们有哪些异同。
101 0