這篇是上一篇的延續:
用ssm(spring+springMVC+mybatis)創建一個簡單的查詢實例(一)
源代碼在github上可以下載,地址:https://github.com/guoxia0719/ssm-select
這篇就根據實際文件進行梳理:
首先已經確定的文件有:Person PersonMapper PersonMapper.xml jdbc.properties
這些有的自動生成的文件方法較多,僅測試了其中一個方法,其他的沒有去除,有興趣的可以自己測試下效果。
工程的目錄結構如下圖所示:紅色框框中的部分是此次需求需要用到的文件,每個文件都有部分說明
下面,針對每個文件進行下說明,說明的順序和圖中文件的列表順序同:
PersonController文件:
package com.one.controller; import com.one.entity.Person; import com.one.service.PersonService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; /** * @Author: guopengxia * @Date: 2019/3/17 13:02 * @Version: 1.0 */ @Controller @RequestMapping("/person") public class PersonController { @Resource PersonService personService; @RequestMapping(value="/select", produces = "text/plain;charset=utf-8") public ModelAndView getPerson(@RequestParam("id")String id){ Person p=personService.getPerson(Integer.parseInt(id)); ModelAndView mav=new ModelAndView("success"); mav.addObject("p",p); return mav; } }
文件中的@Controller表示可以用於匹配用戶請求的url信息, @RequestMapping("/person")用於匹配具體的url的值,這個字段可以分開寫到類上面一部分,寫到方法上一部分
如上面的實例部分,也可以直接寫到方法上(@RequestMapping("/person/select")),
PersonMapper.Java文件:
package com.one.dao; import com.one.entity.Person; public interface PersonMapper { int deleteByPrimaryKey(Integer id); int insert(Person record); Person selectByPrimaryKey(Integer id); //僅僅測試了這一個方法,其他的方法有興趣可以自己做下測試 int updateByPrimaryKey(Person record); }
這個接口和PersonMapper映射文件是一一對應關系,接口中的方法可以綁定到映射文件中的SQL的ID上,二映射文件PersonMapper中的namespace是PersonMapper的路徑名
com.one.entity.Person.selectByPrimaryKey可以定位到映射文件中namespace=com.one.entity.Person,對應的SQL的ID=selectByPrimaryKey,就可以具體執行SQL語句了
PersonMapper.xml文件:
<?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="com.one.dao.PersonMapper" > <resultMap id="BaseResultMap" type="com.one.entity.Person" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="remark" property="remark" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, name, password, remark </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from person where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from person where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.one.entity.Person" > insert into person (id, name, password, remark) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR}) </insert> <update id="updateByPrimaryKey" parameterType="com.one.entity.Person" > update person set name = #{name,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, remark = #{remark,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper>
服務類的文件;
PersonService.java文件的內容是:
package com.one.service; import com.one.entity.Person; /** * @Author: guopengxia * @Date: 2019/3/17 15:08 * @Version: 1.0 */ public interface PersonService{ Person getPerson(int id); }
這個接口,主要是定義了對外提供的 接口方法,可以封裝具體的操作實現,便於維護
服務接口的實現類:PersonServiceImpl.java
package com.one.service.impl; import com.one.dao.PersonMapper; import com.one.entity.Person; import com.one.service.PersonService; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * @Author: guopengxia * @Date: 2019/3/17 13:03 * @Version: 1.0 */ @Service("personService") public class PersonServiceImpl implements PersonService { @Resource PersonMapper personMapper; public Person getPerson(int id){ return personMapper.selectByPrimaryKey(id); } }
這個類中具體通過接口實現了業務邏輯功能,通過調用接口的方法進行查詢用戶的信息。
數據庫信息的配置:
jdbc.driverClass=com.mysql.jdbc.Driver jdbc.connectionURL=jdbc:mysql://localhost:3306/fis?useUnicode=true&characterEncoding=utf-8 jdbc.userId=root jdbc.password=#### #jdbc.driverLocation=E:\\Java\\MySQL\\mysql-connector-java-5.1.43\\mysql-connector-java-5.1.43\\mysql-connector-java-5.1.43-bin.jar ##Oracle 數據庫驅動 #jdbc.driver=oracle.jdbc.driver.OracleDriver ##jdbc:mysql://連接地址:端口號(默認3306)/數據庫名 #jdbc.url=jdbc:oracle:thin:@10.1.104.xx:1521:xxxx ##用戶名 #jdbc.username=lis ##密碼 #jdbc.password=hxkf#xxx ##連接池初始化連接 #jdbc.initialSize=10 ##連接池最大連接數 #jdbc.maxActive=100 ##連接池最大空閑連接 #jdbc.maxIdle=0 ##連接池最小空閑連接 #jdbc.minIdle=0 ##等待超時 #jdbc.maxWait=5000 # ##線程池 ##------------ Task ------------ #task.core_pool_size=5 #task.max_pool_size=100 #task.queue_capacity=1000 #task.keep_alive_seconds=60
上面的沒有注釋部分是此次工程中需要的,下面是配置線程池的一些信息,可以自動忽略
spring-mvc.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 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 "> <!-- 組件掃描@Controller,@Service組件對象 --> <context:component-scan base-package="com.one.service.impl;com.one.controller"></context:component-scan> <!-- 啟動SpringMVC的注解功能,完成請求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> </bean> <!-- 定義跳轉的文件的前后綴 ,視圖模式配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 注解掃描 --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
spring-mybatis.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 引入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.driverClass}" /> <property name="url" value="${jdbc.connectionURL}" /> <property name="username" value="${jdbc.userId}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- 配置spring與mybatis結合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 --> <property name="mapperLocations" value="classpath*:com/one/mapper/*.xml"/> </bean> <!-- DAO接口所在包名,Spring會自動查找其下的類 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.one.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- Spring事務控制(注解配置) --> <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 這個必須配置,否則事物不起作用 --> <!-- 支持@Transactional注解支持 --> <!-- 帶有@Transactional標記的方法會自動調用txManager管理事務 --> </beans>
這個文件中的下面是配置事務的,這次簡單查詢不涉及的事務,僅僅是簡單的查詢功能,所以可以把下面的事務自動忽略
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="index.jsp" name="fm" method="post"> username:<input type="text" name="username"/> password:<input type="password" name="password"/> <br> <input type="submit" name="submit" value="提交"/> </form> </body> </html>
響應文件success.jsp:
<%@ page language="java" contentType="text/html;charset=UTF-8" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Title</title> </head> <body> 用戶信息查詢成功!<br> 用戶信息是: 用戶id: ${requestScope.p.id} 用戶名:${requestScope.p.name} 密碼:${requestScope.p.password} 備注:${requestScope.p.remark} </body> </html>
最后是pom.xml文件中導入的依賴jar包,問內容如下所示:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.three</groupId> <artifactId>testweb</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>testweb Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.5.4</version> </dependency> <!--Mybatis Spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <!--slf4j--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.9.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.9.RELEASE</version> </dependency> </dependencies> <build> <finalName>testweb</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!-- mybatis逆向工程 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <!--配置文件的位置--> <configurationFile>src/main/resources/Personal-GeneratorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </pluginManagement> <resources> <resource> <directory>src/main/java</directory><!--所在的目錄--> <includes><!--包括目錄下的.properties,.xml文件都會掃描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
至此,所有的文件都已經改造完畢,下面就是進行測試部分:
1.配置IDEA中的數據庫部分,如下圖所示,點擊IDEA中的右邊database:
選擇MySQL后,進行圖中配置:
配置成功以后,進行tomcat的配置,配置截圖如下所示:按照紅色框框中的進行配置
圖中的部署部分的截圖如下所示:
配置完以后,點擊 apply ,最后OK即可。
下面就可以啟動項目工程了,點擊tomcat旁邊的綠色三角,就可以啟動工程了,出現篇幅一中所示結果:
http://localhost:8080/,運行后可以出現
查詢后,結果如下所示:
到此,真個項目就結束了,不過下面還有一些經常出現的常見性錯誤,由於篇幅問題,在單獨寫一份。
路徑連接如下: