一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - Java環境中MyBatis與Spring或Spring MVC框架的集成方法

Java環境中MyBatis與Spring或Spring MVC框架的集成方法

2020-05-08 11:45czj4451 JAVA教程

和MyBatis類似,Spring或者Spring MVC框架在Web應用程序的運作中同樣主要負責處理數據庫事務,這里我們就來看一下Java環境中MyBatis與Spring或Spring MVC框架的集成方法

與Spring3集成
Spring作為基礎框架,可以集成后端框架,如Hibernate,MyBatis等。

前面是介紹單獨使用MyBatis的,大致邏輯是:
sqlSessionFactory <- configuration file (包括數據庫連接配置)
IXxxMapper <- sqlSession <- sqlSessionFactory
                     <- mapper interface <- mapper xml
得到IxxMapper后,就可以調用其方法進行數據交互了。

和Spring集成時,上面的這些對象需要作為bean來管理:
dataSource bean <- 數據庫連接配置
sqlSessionFactory bean <- dataSource
                                     <- configuration file
userMapper bean <- sqlSessionFactory
                          <- mapper interface
1. 在pom.xml中加入依賴:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<properties>
 <mybatis.spring.version>1.2.1</mybatis.spring.version>
 <dbcp.version>1.4</dbcp.version>
 <spring.version>3.1.2.RELEASE</spring.version>
</properties>
 
<dependencies>
 <dependency><!-- mybatis的幾個對象包裝成spring的bean -->
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>${mybatis.spring.version}</version>
 </dependency>
 <dependency><!-- spring上下文用spring-jdbc連接數據庫 -->
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${spring.version}</version>
 </dependency>
 <dependency><!-- dataSource是BasicDataSource的實例 -->
  <groupId>commons-dbcp</groupId>
  <artifactId>commons-dbcp</artifactId>
  <version>${dbcp.version}</version>
 </dependency>
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${spring.version}</version>
 </dependency>
</dependencies>

2. 在類路徑下創建beans-da.xml文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"><!-- 數據庫連接bean -->
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/hbatis?characterEncoding=utf8" />
  <property name="username" value="root" />
  <property name="password" value="123456" />
 </bean>
  
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- sqlSessionFactory bean -->
  <property name="dataSource" ref="dataSource" /><!-- 數據源 -->
  <property name="configLocation" value="classpath:Configuration.xml" /><!-- 配置文件 -->
 </bean>
  
 <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"><!-- user映射bean-->
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="mapperInterface" value="com.john.hbatis.mapper.IUserMapper" /><!-- 映射接口 -->
 </bean>
</beans>

3. 測試類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@ContextConfiguration(locations = { "classpath:beans-da.xml" })
public class SpringIntegrationTest extends AbstractTestNGSpringContextTests {
  private static final Logger log = LoggerFactory.getLogger(SpringIntegrationTest.class);
   
  @Resource
  IUserMapper mapper;
   
  @Test
  public void queryTest() {
    User user = mapper.getUserById(1);
    log.info("Name: {}, address: {}", user.getName(), user.getAddress());
  }
}

與SpringMVC集成
這里我們建立在與Spring3集成基礎上來講:
1. 往pom.xml添加SpringMVC和Freemarker依賴:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<properties>
 <freemarker.version>2.3.19</freemarker.version>
 <servlet.version>2.5</servlet.version>
</properties>
 
<dependency
 <groupId>org.freemarker</groupId
 <artifactId>freemarker</artifactId
 <version>${freemarker.version}</version
</dependency>
<dependency>
 <groupId>javax.servlet</groupId
 <artifactId>servlet-api</artifactId
 <version>${servlet.version}</version>
 <scope>provided</scope>
</dependency>

2. 在web.xml中加入Spring的監聽器和SpringMVC的servlet:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class><!-- 監聽容器事件,初始化和關閉Web應用上下文并調用ContextCleanupListener清理資源 -->
</listener>
<listener>
 <listener-class>org.springframework.web.context.ContextCleanupListener</listener-class><!-- Web應用關閉時,清理ServletContext中spring相關的可銷毀資源 -->
</listener>
 
<servlet>
 <servlet-name>hbatis</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <!--<init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/hbatis-servlet.xml</param-value>
 </init-param>--><!-- 未配置時,SpringMVC會到WEB-INF目錄下找${project.name}-servlet.xml -->
 <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
 <servlet-name>hbatis</servlet-name>
 <url-pattern>*.htm</url-pattern>
</servlet-mapping>

3. 在WEB-INF下新建:

Spring配置文件applicationContext.xml:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:property-placeholder location="classpath:/database.properties" /><!-- 數據庫配置文件 -->
 
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  p:driverClassName="${driverClassName}"
  p:url="${url}"
  p:username="${user_name}"
  p:password="${password}" /><!-- 數據源配置 -->
  
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- sqlSessionFactory對象 -->
  <property name="dataSource" ref="dataSource" /><!-- 數據源 -->
  <property name="configLocation" value="classpath:Configuration.xml" /><!-- myBatis配置文件 -->
  <!--<property name="mapperLocations" value="classpath*:com/john/hbatis/model/*.xml" />--><!-- 可以在Configuration.xml或此處配置映射文件,但其中不能有相同id的parameterMap, resultMap或sql等 -->
 </bean>
  
 <bean id="mapperConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 掃描指定包以獲取映射器 -->
  <property name="basePackage" value="com.john.hbatis.mapper" />
 </bean>
</beans>

類路徑下的database.properties:

?
1
2
3
4
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
user_name=root
password=123456


注:因為MapperScannerConfigurer可能會導致username取的是系統用戶的賬號,而造成數據庫連接失敗,所以改成其它值:user_name。

SpringMVC配置文件hbatis-servlet.xml:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?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:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
 <mvc:annotation-driven /><!-- 注冊RequestMappingHandlerMapping, RequestMappingHandlerAdapter和ExceptionHandlerExceptionResolver以提供對@RequestMapping,@ExceptionHandler等注解的支持 -->
 
 <context:component-scan base-package="com.john.hbatis.controller" /><!-- 掃描控制器包下有特定注解的類,并實例化和依賴注入 -->
 
 <!-- FreeMarker視圖處理器 -->
 <bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"
  <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/> 
  <property name="contentType" value="text/html;charset=utf-8"/> 
  <property name="prefix" value="" /> 
  <property name="cache" value="false"/> 
  <property name="viewNames"
    <array
      <value>*.ftl</value
    </array
  </property
  <!--<property name="suffix" value=".ftl"/>-->
  <property name="order" value="0"/><!-- 優先級,數值越小優先級越高 -->
 </bean>
 
 <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"
  <property name="templateLoaderPaths"
    <list
      <value>/WEB-INF/ftl/</value><!-- 模板加載路徑 -->
    </list
  </property
 </bean>
</beans>

4. MVC:
控制層:UserController.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Controller
@RequestMapping("/article")
public class UserController {
 
  @Autowired
  IUserMapper mapper;
 
  @RequestMapping("/list")
  public String showAll(ModelMap modelMap) {
    List<Article> articles = mapper.getArticlesByUserId(1);
    modelMap.addAttribute("articles", articles);
    return "main.ftl";
  }
}

視圖層:main.ftl:

?
1
2
3
<#list articles as article>
  <div>${article.id}. ${article.title}: ${article.content}</div>
</#list>

5. 啟動工程,瀏覽器輸入:http://localhost:8080/hbatis/article/list.htm查看結果。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: b站免费网站入口 | 日本深夜影院 | 国人精品视频在线观看 | 亚洲国产日韩成人综合天堂 | 欧美1 | 国产午夜亚洲精品不卡 | 海角社区在线登录 | videosxxxx老女人| 丰满的闺蜜2中文字幕 | 国产成人精品一区二三区 | 白丝憋尿 | 国产精品久久国产精品99盘 | 扒开斗罗美女了的胸罩和内裤漫画 | bbbbbbaaaaaa毛片 | 手机av影院| 久久午夜夜伦痒痒想咳嗽P 久久无码AV亚洲精品色午夜麻豆 | 福利视频一区二区牛牛 | 湖南美女被黑人4p到惨叫 | 我和黑色丝袜班主任 | 国产乱插 | 亚洲另类中文字幕 | 亚洲精品乱码久久久久久蜜桃 | 国产精品福利在线观看入口 | 美女林柏欣21p人体之仓之梦 | 亚洲国产精品一区二区三区久久 | 国产第一自拍 | 成人高辣h视频一区二区在线观看 | 第一次做m被调教经历 | 成人观看免费观看视频 | 久久99re2热在线播放7 | 精品一区二区三区高清免费观看 | 免费超级乱淫播放手机版 | 国产在线视频在线观看 | 小仙夜晚慰自催眠mp3护士篇 | 色综合久久九月婷婷色综合 | 半挠脚心半黄的网站 | a∨在线观看 | 398av影院视频在线 | boobsmilking流奶水| 小妇人电影免费完整观看2021 | 国产精品1 |