javascript
使用IDEA整合SpringMVC和Mybatis(SSM框架)(二)
上一篇已經搭建了一個基礎的springMVC項目,現在加入mybatis的相關配置。
寫代碼之前先在數據庫中建一張表,如下sql:
DROP TABLE IF EXISTS `user_info`; CREATE TABLE `user_info` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,`age` int(11) NULL DEFAULT NULL,`add` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;-- ---------------------------- -- Records of user_info -- ---------------------------- INSERT INTO `user_info` VALUES (1, '劉德華', 12, '香港', 'liu123'); INSERT INTO `user_info` VALUES (2, '張學友', 23, '香港', 'zhang123');SET FOREIGN_KEY_CHECKS = 1;一、修改pom.xml文件,引入依賴包。
<!-- 添加mybatis依賴 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><!-- 添加mybatis/spring整合包依賴 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.2</version></dependency><!-- 添加mysql驅動依賴 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql-driver.version}</version></dependency><!-- 添加數據庫連接池依賴 --><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency><!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 --><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency>二、在web.xml文件中增加mybatis的配置信息。
如下:
<!-- Spring和MyBatis的配置文件 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mybatis.xml</param-value></context-param>三、很明顯我需要在resource文件夾下增加spring-mybatis.xml配置文件。
如下:
<?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:p="http://www.springframework.org/schema/p"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsd"><!-- 自動掃描文件夾根據注解注冊為bean,排除Controller注解的--><!--<context:component-scan base-package="top.byk.controller">--><!--<context:exclude-filter type="annotation"--><!--expression="org.springframework.stereotype.Controller" />--><!--</context:component-scan>--><!-- 添加JDBC數據源,指定一個配置文件 --><context:property-placeholder location="classpath:jdbc.properties" /><!-- 這里用到了DBCP,自動管理數據庫連接的釋放和斷開 --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><!-- 初始化物理連接數 --><property name="initialSize" value="${jdbc.initialSize}" /><!-- 連接池最大數量 --><property name="maxActive" value="${jdbc.maxActive}" /><!-- 連接池最大空閑 --><property name="maxIdle" value="${jdbc.maxIdle}" /><!-- 連接池最小空閑 --><property name="minIdle" value="${jdbc.minIdle}" /><!-- 獲取連接最大等待時間 --><property name="maxWait" value="${jdbc.maxWait}" /></bean><!-- spring和MyBatis完美整合,不需要MyBatis的配置映射文件 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><!-- 加載MyBatis的一個小配置文件 --><property name="configLocation" value="classpath:/mybatis-config.xml"/><!-- 自動掃描mapping.xml文件 --><property name="mapperLocations" value="classpath:/mapper/userMapper.xml" /></bean><!-- 根據指定的Mapper接口生成Bean實例 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="top.byk.dao"/><!-- 注意:下邊這句是在有多個sqlSessionFactory時加的, --><!-- 同時,注意它的name和value,后邊的不能是ref --><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean><!-- 事務管理 --><tx:annotation-driven transaction-manager="txManager" /><bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean> </beans>四、
根據spring-mybatis.xml配置文件,我們需要增加兩個新的文件:jdbc.properties和mybatis-config.xml文件。
先增加jdbc.properties文件信息:
jdbc.driver=com.mysql.jdbc.Driver #jdbc.url=jdbc:mysql://192.168.169.233:3306/yysd-zx-new?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true jdbc.username=root jdbc.password=123456# 初始化物理連接數 jdbc.initialSize=0 # 最大連接池數目 jdbc.maxActive=20 # 最大空閑連接 jdbc.maxIdle=20 # 最小空閑連接 jdbc.minIdle=11 # 獲取連接最大等待時間 jdbc.maxWait=60000然后再增加mybatis-config.xml文件信息,如果不需要特殊配置的話直接注釋掉相關引入語句即可:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration><!-- 此處可以定義別名 --><typeAliases><!--<typeAlias alias="product" type="com.holystar.entity.Product"/>--></typeAliases></configuration>五、UserMapper.xml
在resource文件夾下新增/mapper/UserMapper.xml文件,進行數據庫的映射和相關sql的書寫。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="top.byk.dao.UserMapper"><resultMap id="baseMap" type="top.byk.entity.User"><id column="id" property="id" jdbcType="INTEGER"/><result column="name" property="name" jdbcType="VARCHAR"/><result column="add" property="add" jdbcType="VARCHAR"/><result column="password" property="password" jdbcType="VARCHAR"/><result column="age" property="age" jdbcType="INTEGER"/></resultMap><select id="getAll" resultMap="baseMap">select * from user_info;</select> </mapper>六、UserMapper.java
這個接口文件的路徑必須和剛才的UserMapper.xml中的namespace保持一致。idea的好處就是按住ctrl鍵點擊文件名,直接可以跳到相關的文件,可以用來檢驗UserMapper文件的位置是否正確。
查詢方法名必須和<select> 標簽中的id相同。
@Repository public interface UserMapper {List<User> getAll(); }七、User.java
top.byk.entity文件夾下增加User.java 實體類,同樣的檢驗方法。
public class User {private int id;private String name;private String add;private String password;private int age;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAdd() {return add;}public void setAdd(String add) {this.add = add;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", add='" + add + '\'' +", password='" + password + '\'' +", age=" + age +'}';}八、service和controller
下面的代碼就很簡單了。
service接口以及serviceImpl實現類。
public interface UserService {List<User> getAll(); } @Service public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic List<User> getAll() {return userMapper.getAll();} }controller代碼,分別測試了三種傳值方式:
@Controller @RequestMapping("/user") public class UserController {@Resourceprivate UserService userService;@RequestMapping(value = "toUser",method = RequestMethod.GET)public String toUser(){return "user";}@RequestMapping(value = "model",method = RequestMethod.GET)public String model(Model model){List<User> userList = userService.getAll();model.addAttribute("user","劉德華");model.addAttribute("user1",userList.get(1));return "user";}@RequestMapping(value = "modelAndView",method = RequestMethod.GET)public ModelAndView modelAndView(){ModelAndView modelAndView = new ModelAndView();modelAndView.setViewName("user");List<User> userList = userService.getAll();modelAndView.addObject("userList",userList);return modelAndView;}九、user.jsp頁面
看來我們還得寫一個user.jsp頁面。這個頁面也很簡單,主要是引入 C 標簽和取值。如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head><title>Title</title> </head> <body> <h1>這是user.jsp頁面</h1> <h1>我是${user}</h1> <h1>我是${user1.name},我今年${user1.age}歲,我住在${user1.add},我的密碼是${user1.password}</h1><ul><c:forEach var="user" items="${userList}"><li>編號:${user.id},姓名:${user.name},年齡:${user.age},住址:${user.add},密碼:${user.password}</li></c:forEach> </ul> </body> </html>十、訪問
啟動項目,瀏覽器訪問。
訪問http://localhost:8080/user/model,效果如下:
訪問?http://localhost:8080/user/modelAndView,如下:
十一、總結
問題一、創建項目之前,參考了很多網上的列子,復制了很多別人的配置文件。結果就是邯鄲學步,controller,service和dao層都是多次注入,最終爆出了一個
NoSuchBeanDefinitionException:? No qualifying bean of type [lf.service.UserService] found for dependency:? expected at least 1 bean which qualifies as autowire candidate for this dependency.? Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}找了半天,@Autowired改成@Resource,或者給@Service加value屬性,都嘗試過。
最終重要知道原因所在,因為service注入了兩次?;舅悸肪褪莿h掉相關的注入語句,只保留一個即可。
問題二、提示找不到mybatis-config.xml文件。
class path resource [mybatis-config.xml] cannot be opened because it does not exist怎么會找不到呢,我按著ctrl建點擊都能進去,證明我的引入路徑是沒問題的,也不是沒掃描到啊。按網上的方法重新Mark Directory as,也沒用。靈感突現,刪掉了target文件。然后重新編譯項目。好了。不可描述的心情。
十二、源碼
https://github.com/bian1234/MySSMDemo
總結
以上是生活随笔為你收集整理的使用IDEA整合SpringMVC和Mybatis(SSM框架)(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据中心分析诊断必备之常用仪表
- 下一篇: Spring Boot使用Commons