💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
spring+springmvc+Mybatis整合 ***** 一.**pom.xml **代码 ~~~ <?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.youge</groupId> <artifactId>SSM</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>SSM 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.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.2.9.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- 事务--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.19</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--log start--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.30</version> </dependency> <!--log end--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.3</version> </dependency> <!-- 数据库连接池--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> <build> <finalName>SSM</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> </plugins> </pluginManagement> </build> </project> ~~~ ***** 二.`web.xml`代码 ~~~ <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!-- 配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 设置配置文件的路径--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 加载springmvc.xml配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 解决中文的乱码的过滤器--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ~~~ ***** 三.`springmvc.xml`代码 ~~~ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--开启注解扫描,只扫描Controller注解--> <context:component-scan base-package="com.youge"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置视图解析器对象--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 过滤静态资源--> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <mvc:resources mapping="/css/**" location="/css/"></mvc:resources> <mvc:resources mapping="/images/**" location="/images/"></mvc:resources> <!-- 开启SpringMVC注解的支持--> <mvc:annotation-driven /> </beans> ~~~ ***** 四.`applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描,只希望处理service和dao,controller不需要Spring框架去处理--> <context:component-scan base-package="com.youge"> <!-- 配置哪些注解不扫描--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- Spring整合MyBatis框架--> <!-- 配置连接池--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db1?serverTimezone=UTC"/> <property name="user" value="root"/> <property name="password" value="admin123"/> </bean> <!-- 配置SqlSessionFactory工厂--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 配置AccountDao接口所在包--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScanner"> <property name="basePackage" value="com.youge.dao" /> </bean> <!-- 配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT" /> </tx:attributes> </tx:advice> <!-- 配置AOP增加--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.youge.service.impl.*ServiceImpl.*(..))" /> </aop:config> </beans> ~~~ ***** 五.`log4j.properties`代码 ~~~ log4j.rootLogger=DEBUG, stdout, logfile log4j.category.org.springframework=ERROR log4j.category.org.apache=INFO log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n log4j.appender.logfile=org.apache.log4j.RollingFileAppender log4j.appender.logfile.File=${myweb.root}/WEB-INF/log/myweb.log log4j.appender.logfile.MaxFileSize=512KB log4j.appender.logfile.MaxBackupIndex=5 log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n ~~~ ***** 六.`SqlMapConfig.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> <!-- 整合mybatis后,该配置文件可以删除--> <!-- 配置环境--> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/db1?serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="admin123"/> </dataSource> </environment> </environments> <!-- 引入映射配置文件--> <mappers> <!-- <mapper class="com.youge.dao.AccountDao"></mapper>--> <package name="com.youge.dao"/> </mappers> </configuration> ~~~ ***** 七.`index.jsp`代码 ~~~ <%-- Created by IntelliJ IDEA. User: Administrator Date: 2020-09-28 Time: 15:47 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="account/findAll">测试查询</a> <h3>测试保存</h3> <form action="/account/save" method="post"> 姓名: <input type="text" name="name"> <br> 金额: <input type="text" name="balance" > <br> <input type="submit" value="保存"> </form> </body> </html> ~~~ 八`.list.jsp`代码 ~~~ <%-- Created by IntelliJ IDEA. User: Administrator Date: 2020-09-28 Time: 21:43 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>list</title> </head> <body> <h2>查询所有账户</h2> <c:forEach items="${list}" var="account"> ${account.name}<br> ${account.balance}<br> </c:forEach> </body> </html> ~~~ ***** 九.`AccountDao.java`代码 ~~~ package com.youge.dao; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-28 18:30 */ import com.youge.domain.Account; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; /** * 账户dao接口 */ @Repository public interface AccountDao { //查询所有账户 @Select("select * from account") public List<Account> findAll(); //保存账户信息 @Insert("insert into account(name,balance) values(#{name},#{balance})") public void saveAccount(Account account); } ~~~ ***** 十`.Account.java`代码 ~~~ package com.youge.domain; import java.io.Serializable; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-28 18:24 */ /** * 账户 */ public class Account implements Serializable { private Integer id; private String name; private Double balance; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", balance=" + balance + '}'; } } ~~~ ***** 十一.`AccountService.java`代码 ~~~ package com.youge.service; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-28 18:38 */ import com.youge.domain.Account; import java.util.List; /** * 服务层接口 */ public interface AccountService { //查询所有账户 public List<Account> findAll(); //保存账户信息 public void saveAccount(Account account); } ~~~ ***** 十二. `AccountServiceImpl.java` 代码 ~~~ package com.youge.service.impl; import com.youge.dao.AccountDao; import com.youge.domain.Account; import com.youge.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-28 18:43 */ @Service("accountService") public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public List<Account> findAll() { System.out.println("业务层:查询所有账户..."); return accountDao.findAll(); } @Override public void saveAccount(Account account) { System.out.println("业务层:保存账户..."); accountDao.saveAccount(account); } } ~~~ ***** 十三.`AccountController.java ` 代码 ~~~ package com.youge.controller; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-28 18:45 */ import com.youge.domain.Account; import com.youge.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * 账户web层 */ @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @RequestMapping("/findAll") public String findAll(Model model) { System.out.println("表现层:查询所有账户...."); List<Account> list = accountService.findAll(); model.addAttribute("list", list); return "list"; } /** * 保存 * * @param account * @return */ @RequestMapping("/save") public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { accountService.saveAccount(account); //重定向 response.sendRedirect(request.getContextPath() + "/account/findAll"); return; } } ~~~ ***** 十四.`TestMyBatis.java`代码 ~~~ package com.youge.test; import com.youge.dao.AccountDao; import com.youge.domain.Account; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-28 22:58 */ public class TestMyBatis { /** * 测试查询 * @throws Exception */ @Test public void run1() throws Exception { // 加载配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建sqlSessionFactory对象 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession对象 SqlSession session = factory.openSession(); //获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class); List<Account> list = dao.findAll(); System.out.println(list); for (Account account : list) { System.out.println(account.getName()); System.out.println(account.getBalance()); } //释放资源 session.close(); in.close(); } /** * 测试保存 * @throws Exception */ @Test public void run2() throws Exception { Account account = new Account(); account.setBalance(1000.58d); account.setName("熊大"); // 加载配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建sqlSessionFactory对象 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); // 创建SqlSession对象 SqlSession session = factory.openSession(); //获取到代理对象 AccountDao dao = session.getMapper(AccountDao.class); dao.saveAccount(account); // 提交事务 session.commit(); //释放资源 session.close(); in.close(); } } ~~~ ***** 十五.`TestSpring.java` 代码 ~~~ package com.youge.test; import com.youge.service.AccountService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-28 19:12 */ public class TestSpring { @Test public void run1(){ //加载配置文件 ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); AccountService as = (AccountService) ac.getBean("accountService"); //调用方法 as.findAll(); } } ~~~