SSM17.4【SSM框架整合--Spring+Mybatis】
搭建和测试Mybatis的开发环境
创建和编写sqlMapConfig.xml配置文件
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/hm_ssm 3 jdbc.username=root 4 jdbc.password=root
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 6 <configuration> 7 8 <!--加载外部properties文件--> 9 <properties resource="jdbc.properties"></properties> 10 11 <!--配置环境--> 12 <environments default="mysql_environment"> 13 <environment id="mysql_environment"> 14 <transactionManager type="JDBC"></transactionManager> 15 <dataSource type="POOLED"> 16 <property name="driver" value="${jdbc.driver}"/> 17 <property name="url" value="${jdbc.url}"/> 18 <property name="username" value="${jdbc.username}"/> 19 <property name="password" value="${jdbc.password}"/> 20 </dataSource> 21 </environment> 22 </environments> 23 24 25 <!--1、加载映射文件(xml实现)--> 26 <!--<mappers> 27 <mapper resource="com/haifei/mapper/UserMapper.xml"/> 28 </mappers>--> 29 <!--2、加载映射关系(注解实现)--> 30 <!--实现方式1:扫接口所在的包--> 31 <mappers> 32 <package name="com.haifei.dao"></package> 33 </mappers> 34 <!--实现方式2:指定接口的全路径--> 35 <!--<mappers> 36 <mapper class="com.haifei.dao.AccountDao" /> 37 </mappers>--> 38 39 40 </configuration>
在AccountDao接口的方法上添加注解,编写SQL语句
1 package com.haifei.dao; 2 3 import com.haifei.domain.Account; 4 import org.apache.ibatis.annotations.Insert; 5 import org.apache.ibatis.annotations.Select; 6 7 import java.util.List; 8 9 /** 10 * dao接口-账户 11 */ 12 public interface AccountDao { 13 14 //查询所有账户 15 @Select("select * from ssm_account") 16 public List<Account> findAll(); 17 18 //保存账户信息 19 @Insert("insert into ssm_account(name,money) values(#{name},#{money})") 20 public void saveAccount(Account account); 21 22 }
测试Mybatis框架是否搭建成功
1 package com.haifei.test; 2 3 import com.haifei.dao.AccountDao; 4 import com.haifei.domain.Account; 5 import org.apache.ibatis.io.Resources; 6 import org.apache.ibatis.session.SqlSession; 7 import org.apache.ibatis.session.SqlSessionFactory; 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 9 import org.junit.Test; 10 11 import java.io.IOException; 12 import java.io.InputStream; 13 import java.util.List; 14 15 public class TestMybatis { 16 17 /** 18 * 测试查询 19 * @throws Exception 20 */ 21 @Test 22 public void run1() throws Exception { 23 //加载配置文件 24 InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml"); 25 //创建SqlSessionFactory对象 26 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); 27 //创建SqlSession对象 28 SqlSession session = factory.openSession(); 29 //获取代理对象 30 AccountDao dao = session.getMapper(AccountDao.class); 31 //调用方法 32 List<Account> accountList = dao.findAll(); 33 for (Account account : accountList) { 34 System.out.println(account); 35 } 36 //关闭/释放资源 37 session.close(); 38 is.close(); 39 } 40 /* 41 Account{id=1, name='zhangsan', money=1000.0} 42 Account{id=2, name='lisi', money=2000.0} 43 Account{id=3, name='wangwu', money=3000.0} 44 */ 45 46 /** 47 * 测试保存 48 * @throws Exception 49 */ 50 @Test 51 public void run2() throws Exception { 52 //加载配置文件 53 InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml"); 54 //创建SqlSessionFactory对象 55 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); 56 //创建SqlSession对象 57 SqlSession session = factory.openSession(true); //设置为true-->session.commit(); 58 //获取代理对象 59 AccountDao dao = session.getMapper(AccountDao.class); 60 //调用方法 61 Account account = new Account(); 62 account.setName("tom"); 63 account.setMoney(400D); //Double包装类 64 dao.saveAccount(account); 65 //关闭/释放资源 66 session.close(); 67 is.close(); 68 } 69 70 }
Spring整合Mybatis
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context.xsd 12 http://www.springframework.org/schema/aop 13 http://www.springframework.org/schema/aop/spring-aop.xsd 14 http://www.springframework.org/schema/tx 15 http://www.springframework.org/schema/tx/spring-tx.xsd 16 "> 17 18 19 <!--开启注解所需的组件扫描,期望spring只负责处理service和dao;controller用springMVC处理--> 20 <context:component-scan base-package="com.haifei"> 21 <!--配置哪些注解不被扫描--> 22 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 23 </context:component-scan> 24 25 26 <!--Spring整合Mybatis框架--> 27 <!--1、加载外部的properties文件--> 28 <context:property-placeholder location="classpath:jdbc.properties"/> 29 <!--2、配置数据源(数据库连接池)--> 30 <bean id="dataSource_c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 31 <property name="driverClass" value="${jdbc.driver}"></property> 32 <property name="jdbcUrl" value="${jdbc.url}"></property> 33 <property name="user" value="${jdbc.username}"></property> 34 <property name="password" value="${jdbc.password}"></property> 35 </bean> 36 <bean id="dataSource_druid" class="com.alibaba.druid.pool.DruidDataSource"> 37 <property name="driverClassName" value="${jdbc.driver}"></property> 38 <property name="url" value="${jdbc.url}"></property> 39 <property name="username" value="${jdbc.username}"></property> 40 <property name="password" value="${jdbc.password}"></property> 41 </bean> 42 <!--<!–配置spring jdbcTemplate–> 43 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 44 <property name="dataSource" ref="dataSource_c3p0"/> 45 </bean>--> 46 <!--3、配置SqlSessionFactory工厂--> 47 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 48 <property name="dataSource" ref="dataSource_c3p0" /> <!--数据源可选c3p0和druid--> 49 </bean> 50 <!--4、配置AccountDao接口所在包--> 51 <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 52 <property name="basePackage" value="com.haifei.dao"/> 53 </bean> 54 <!--/Spring整合Mybatis框架(以上配置完成后,sqlMapConfig.xml可以删掉了)--> 55 56 57 <!--配置Spring框架的声明式事务管理--> 58 <!--1、配置事务管理器--> 59 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 60 <property name="dataSource" ref="dataSource_c3p0"/> <!--数据源可选c3p0和druid--> 61 </bean> 62 <!--2、配置事务通知--> 63 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 64 <tx:attributes> 65 <tx:method name="find*" read-only="true"/> <!--以find开头的方法设置为只读--> 66 <tx:method name="*" isolation="DEFAULT"/> <!--除了以find开头的方法设置,例如隔离级别设置为默认--> 67 </tx:attributes> 68 </tx:advice> 69 <!--3、配置AOP增强--> 70 <aop:config> 71 <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.haifei.service.impl.*ServiceImpl.*(..))" /> 72 <!--public可以省略不写 返回值为* impl包下的*ServiceImpl类中的所有方法,且任意类型的参数--> 73 <!--对以上描述的方法进行增强--> 74 </aop:config> 75 <!--/配置Spring框架的声明式事务管理--> 76 77 78 </beans>
1 package com.haifei.dao; 2 3 import com.haifei.domain.Account; 4 import org.apache.ibatis.annotations.Insert; 5 import org.apache.ibatis.annotations.Select; 6 import org.springframework.stereotype.Repository; 7 8 import java.util.List; 9 10 /** 11 * dao接口-账户 12 */ 13 @Repository //将dao层类交给spring的IOC容器进行管理,实例化bean 14 public interface AccountDao { 15 16 //查询所有账户 17 @Select("select * from ssm_account") 18 public List<Account> findAll(); 19 20 //保存账户信息 21 @Insert("insert into ssm_account(name,money) values(#{name},#{money})") 22 public void saveAccount(Account account); 23 24 }
1 package com.haifei.service.impl; 2 3 import com.haifei.dao.AccountDao; 4 import com.haifei.domain.Account; 5 import com.haifei.service.AccountService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 9 import java.util.List; 10 11 /** 12 * service接口实现类-账户 13 */ 14 @Service("accountService") //将service层类交给spring的IOC容器进行管理,实例化bean 15 public class AccountServiceImpl implements AccountService { 16 17 @Autowired //根据类型进行自动注入 18 private AccountDao accountDao; 19 20 @Override 21 public List<Account> findAll() { 22 System.out.println("业务层:查询所有账户"); 23 return accountDao.findAll(); 24 } 25 26 @Override 27 public void saveAccount(Account account) { 28 System.out.println("业务层:保存账户信息"); 29 accountDao.saveAccount(account); 30 } 31 32 }
1 package com.haifei.controller; 2 3 import com.haifei.domain.Account; 4 import com.haifei.service.AccountService; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.ui.Model; 8 import org.springframework.web.bind.annotation.RequestMapping; 9 import org.springframework.web.servlet.ModelAndView; 10 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 import java.io.IOException; 14 import java.util.List; 15 16 /** 17 * web层-账户 18 */ 19 @Controller //将web层类交给spring的IOC容器进行管理,实例化bean 20 @RequestMapping("/account") 21 public class AccountController { 22 23 @Autowired //根据类型进行自动注入 24 private AccountService accountService; 25 26 @RequestMapping("/findAll") 27 public String findAll(Model model){ 28 System.out.println("表现层:查询所有账户信息"); 29 List<Account> accountList = accountService.findAll(); 30 model.addAttribute("accountList", accountList); 31 return "list"; 32 } 33 /*@RequestMapping("/findAll") 34 public ModelAndView findAll(ModelAndView modelAndView){ 35 System.out.println("表现层:查询所有账户信息"); 36 List<Account> accountList = accountService.findAll(); 37 modelAndView.addObject("accountList", accountList); 38 modelAndView.setViewName("list"); 39 return modelAndView; 40 }*/ 41 42 @RequestMapping("/save") 43 public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException { 44 System.out.println("表现层:保存账户信息"); 45 accountService.saveAccount(account); 46 response.sendRedirect(request.getContextPath() + "/account/findAll"); //重定向至查询功能 47 } 48 49 }
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>index.jsp</title> 5 </head> 6 <body> 7 <a href="account/findAll">测试查询</a> 8 <hr> 9 <h2>测试保存</h2> 10 <form action="account/save" method="post"> 11 姓名:<input type="text" name="name" /><br/> 12 金额:<input type="text" name="money" /><br/> 13 <input type="submit" value="保存"/><br/> 14 </form> 15 </body> 16 </html>
1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> 2 <%--https://blog.csdn.net/fyqcdbdx/article/details/6317579--%> 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 <html> 5 <head> 6 <title>list.jsp</title> 7 </head> 8 <body> 9 <h2>查询到所有账户信息,在此页面展示</h2> 10 <c:forEach items="${accountList}" var="account"> 11 ${account.id}--${account.name}--${account.money}<br> 12 </c:forEach> 13 </body> 14 </html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!