Spring SpringMVC MyBatis 起步(二)
在项目中整合Mybatis
1.在pom.xml中添加mybatis相关的依赖
1 2 <!-- jdbc包连接数据库 --> 3 <dependency> 4 <groupId>org.springframework</groupId> 5 <artifactId>spring-jdbc</artifactId> 6 <version>${spring.version}</version> 7 </dependency> 8 9 <!-- mybatis核心包 --> 10 <dependency> 11 <groupId>org.mybatis</groupId> 12 <artifactId>mybatis</artifactId> 13 <version>${mybatis.version}</version> 14 </dependency> 15 <!-- mybatis/spring包 --> 16 <dependency> 17 <groupId>org.mybatis</groupId> 18 <artifactId>mybatis-spring</artifactId> 19 <version>1.3.2</version> 20 </dependency> 21 22 <!-- 导入Mysql数据库链接jar包 --> 23 <dependency> 24 <groupId>mysql</groupId> 25 <artifactId>mysql-connector-java</artifactId> 26 <version>5.1.36</version> 27 </dependency> 28 <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> 29 <dependency> 30 <groupId>commons-dbcp</groupId> 31 <artifactId>commons-dbcp</artifactId> 32 <version>1.2.2</version> 33 </dependency>
2.进行相关配置
在resources目录下新建配置文件applicationContext.xml配置数据库连接以及mybatis
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xmlns:p="http://www.springframework.org/schema/p" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:mvc="http://www.springframework.org/schema/mvc" 8 xsi:schemaLocation=" 9 http://www.springframework.org/schema/beans 10 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 11 http://www.springframework.org/schema/mvc 12 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 13 http://www.springframework.org/schema/context 14 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 15 16 <context:annotation-config></context:annotation-config> 17 18 <context:component-scan base-package="com.xcz" /> 19 20 <!-- 引入配置文件 --> 21 <bean id="propertyConfigurer" 22 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 23 <property name="location" value="classpath:jdbc.properties" /> 24 </bean> 25 26 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 27 <property name="driverClassName" value="${driver}" /> 28 <property name="url" value="${url}" /> 29 <property name="username" value="${username}" /> 30 <property name="password" value="${password}" /> 31 <!-- 初始化连接大小 --> 32 <property name="initialSize" value="${initialSize}"></property> 33 <!-- 连接池最大数量 --> 34 <property name="maxActive" value="${maxActive}"></property> 35 <!-- 连接池最大空闲 --> 36 <property name="maxIdle" value="${maxIdle}"></property> 37 <!-- 连接池最小空闲 --> 38 <property name="minIdle" value="${minIdle}"></property> 39 <!-- 获取连接最大等待时间 --> 40 <property name="maxWait" value="${maxWait}"></property> 41 </bean> 42 43 <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> 44 <bean id="sqlSessionFactory" 45 class="org.mybatis.spring.SqlSessionFactoryBean"> 46 <property name="dataSource" ref="dataSource" /> 47 <!-- 自动扫描mapping.xml文件 --> 48 <property name="mapperLocations" value="classpath*:com/xcz/mapping/*.xml"></property> 49 </bean> 50 51 <!-- DAO接口所在包名,Spring会自动查找其下的类 --> 52 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 53 <property name="basePackage" value="com.xcz.dao" /> 54 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 55 </bean> 56 57 <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> 58 <bean id="transactionManager" 59 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 60 <property name="dataSource" ref="dataSource" /> 61 </bean> 62 </beans>
在resources目录下新建jdbc.properties,将参数修改为你的mysql的数据库地址、用户名、密码
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/eshop 3 username=root 4 password=123456 5 #定义初始连接数 6 initialSize=0 7 #定义最大连接数 8 maxActive=20 9 #定义最大空闲 10 maxIdle=20 11 #定义最小空闲 12 minIdle=1 13 #定义最长等待时间 14 maxWait=60000
3.从数据库中查询一条用户数据并输出
3.1 使用mybatis-generator创建UserMapper.xml, UserMapper.java, User.java
[ 参考:https://www.cnblogs.com/smileberry/p/4145872.html ]
准备: mybatis-generator-core-1.3.7.jar,mysql-connector-java-5.1.46.jar,mysql-connector-java-5.1.46-bin.jar
讲这三个jar包放在同一目录下,新建generatoConfig.xml,内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 <generatorConfiguration> 6 <!-- 数据库驱动 --> 7 <classPathEntry location="mysql-connector-java-5.1.46-bin.jar" /> 8 <context id="DB2Tables" targetRuntime="MyBatis3"> 9 <commentGenerator> 10 <property name="suppressDate" value="true" /> 11 <!-- 是否去除自动生成的注释 true:是 : false:否 --> 12 <property name="suppressAllComments" value="true" /> 13 </commentGenerator> 14 <!--数据库链接URL,用户名、密码 --> 15 <jdbcConnection driverClass="com.mysql.jdbc.Driver" 16 connectionURL="jdbc:mysql://127.0.0.1:3306/eshop" userId="root" 17 password="123456"> 18 </jdbcConnection> 19 <javaTypeResolver> 20 <property name="forceBigDecimals" value="false" /> 21 </javaTypeResolver> 22 <!-- 生成模型的包名和位置 --> 23 <javaModelGenerator targetPackage="com.xcz.model" 24 targetProject="src"> 25 <property name="enableSubPackages" value="true" /> 26 <property name="trimStrings" value="true" /> 27 </javaModelGenerator> 28 <!-- 生成映射文件的包名和位置 --> 29 <sqlMapGenerator targetPackage="com.xcz.mapping" 30 targetProject="src"> 31 <property name="enableSubPackages" value="true" /> 32 </sqlMapGenerator> 33 <!-- 生成DAO的包名和位置 --> 34 <javaClientGenerator type="XMLMAPPER" 35 targetPackage="com.xcz.dao" targetProject="src"> 36 <property name="enableSubPackages" value="true" /> 37 </javaClientGenerator> 38 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 --> 39 <table tableName="t_users" domainObjectName="User" 40 enableCountByExample="false" enableUpdateByExample="false" 41 enableDeleteByExample="false" enableSelectByExample="false" 42 selectByExampleQueryId="false"></table> 43 </context> 44 </generatorConfiguration>
在根目录处打开控制命令行或power shell
运行 java -jar mybatis-generator-core-1.3.7.jar -configfile generatorConfig.xml -overwrite
得到如下提示则已成功生成代码
生成的代码会按照配置中的路径进行放置
在目录【src/com/xcz/】下可以看到文件夹和文件
然后将其中的文件复制到项目中对应的文件夹内就完成这一步了。
3.2 编写Service层和Controller层
在【com/xcz/service】中新建文件UserService.java
1 package com.xcz.service; 2 3 import org.springframework.stereotype.Service; 4 5 import com.xcz.model.User; 6 7 @Service 8 public interface UserService { 9 10 11 User getUserByUserId(Integer userId); 12 13 }
然后创建一个impl文件夹,里面放置实现接口的类UserServicImpl.java
1 package com.xcz.service.impl; 2 3 import javax.annotation.Resource; 4 5 import org.springframework.stereotype.Service; 6 7 import com.xcz.dao.UserMapper; 8 import com.xcz.service.UserService; 9 import com.xcz.model.User; 10 11 @Service("userService") 12 public class UserServiceImpl implements UserService{ 13 14 @Resource 15 private UserMapper userDao; 16 17 public User getUserByUserId(Integer userId) { 18 return this.userDao.selectByPrimaryKey(userId); 19 } 20 }
在【com/xcz/controller】中新建文件UserController.java
1 package com.xcz.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RequestParam; 7 import org.springframework.web.bind.annotation.ResponseBody; 8 9 import com.xcz.model.User; 10 import com.xcz.service.UserService; 11 12 @Controller 13 @RequestMapping(value = "/user") 14 public class UserController { 15 16 @Autowired 17 private UserService userService; 18 19 @RequestMapping("/get") 20 public @ResponseBody User getUserInfo(@RequestParam("userId") Integer userId) { 21 User user = userService.getUserByUserId(userId); 22 return user; 23 } 24 }
3.3 在浏览器中访问
访问 [ http://localhost:8080/fileReportary/user/get?userId=1 ]
得到结果如下
此时已经成功的获取到了用户ID为1的用户信息
4.过程中可能遇到的问题
4.1 NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
原因:pom.xml中没有引入jstl相关的库
解决办法:加入jstl的依赖
备注:这个地方要注意过滤掉一些包,因为tomcat中已经包含,可能会产生冲突导致项目无法启动
1 <dependency> 2 <groupId>javax.servlet.jsp.jstl</groupId> 3 <artifactId>jstl-api</artifactId> 4 <version>1.2</version> 5 <exclusions> 6 <exclusion> 7 <groupId>javax.servlet</groupId> 8 <artifactId>servlet-api</artifactId> 9 </exclusion> 10 <exclusion> 11 <groupId>javax.servlet.jsp</groupId> 12 <artifactId>jsp-api</artifactId> 13 </exclusion> 14 </exclusions> 15 </dependency> 16 <dependency> 17 <groupId>org.glassfish.web</groupId> 18 <artifactId>jstl-impl</artifactId> 19 <version>1.2</version> 20 <exclusions> 21 <exclusion> 22 <groupId>javax.servlet</groupId> 23 <artifactId>servlet-api</artifactId> 24 </exclusion> 25 <exclusion> 26 <groupId>javax.servlet.jsp</groupId> 27 <artifactId>jsp-api</artifactId> 28 </exclusion> 29 <exclusion> 30 <groupId>javax.servlet.jsp.jstl</groupId> 31 <artifactId>jstl-api</artifactId> 32 </exclusion> 33 </exclusions> 34 </dependency>
4.2 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
原因:依赖包没有引入
解决办法:右键项目-》properties-》Add-》Java Build Path Entries-》Maven Dependenciees
添加成功后如下图,此时再运行就不会报错了
4.3 mybatis-generator 的坑
原因:mybatis-generator 生成的mapper.xml中可能会有重复的内容,会导致编译错误
解决办法:删除掉重复的内容