大家好,又见面了,我是你们的朋友全栈君。
create database ssm;
create table account(
id int primary key auto_increment,
name varchar(100),
money double(7,2),
);
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.yg</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.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</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>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${
mysql.version}</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.0</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>${
log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${
slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${
slf4j.version}</version>
</dependency> <!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${
mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</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>
package com.yg.daomain;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
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 getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
package com.yg.service;
import com.yg.daomain.Account;
import java.util.List;
public interface IAccountService {
public void saveAccount(Account account);
public List<Account> findAll();
}
package cn.itcast.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import cn.itcast.dao.AccountDao;
import cn.itcast.domain.Account;
import cn.itcast.service.AccountService;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
private AccountDao account;
public void saveAccount(Account account) {
}
public List<Account> findAll() {
System.out.println("业务层:查询所有账户...");
return null; }
}
package com.yg.dao;
import com.yg.daomain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
public interface IAccountDao {
public void saveAccount(Account account);
public List<Account> findAll();
}
<?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层的注解。要忽略web层让springmvc去管理-->
<context:component-scan base-package="com.yg">
<!--配置要忽略的注解-->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
import com.yg.dao.IAccountDao;
import com.yg.daomain.Account;
import com.yg.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/** * 账户的业务层实现类 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount(); }
@Override
public void saveAccount(Account account) {
accountDao.saveAccount
} }
持久层实现类代码: 此时不要做任何操作,就输出一句话。目的是测试 spring 框架搭建的结果。
import com.yg.dao.IAccountDao;
import com.yg.daomain.Account;
import org.springframework.stereotype.Repository;
import java.util.List;
/** * 账户的持久层实现类 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Override
public List<Account> findAllAccount() {
System.out.println("查询了所有账户");
return null; }@Override
public void saveAccount(Account account) {
System.out.println("保存了账户");
} }
}
package com.yg.test;
import com.yg.service.IAccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ServiceTest {
@Test
public void testspring() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
IAccountService as = (IAccountService) ac.getBean("accountService");
as.findAll();
}
}
运行结果:
<!--配偶之前端控制器:服务启动必须加载,需要加载的springmvc.xml配置文件-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置初始化参数,创建完DispatcherServlet对象加载springmvc.xml配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--服务启动的时候,让DispatcherServlet对象创建-->
<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>
<?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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描controller的注解,别的不扫描-->
<context:component-scan base-package="com.yg" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"></context:include-filter>
</context:component-scan>
<!--配置视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--JSP文件所在的目录-->
<property name="prefix" value="/WEB-INF/pages/"/>
<!--文件的后缀名-->
<property name="suffix" value=".jsp"/>
</bean>
<!--设置静态资源不过滤-->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<!--开启对springmvc的注解支持-->
<mvc:annotation-driven/>
</beans>
jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>主页</title>
</head>
<body><a href="account/findAllAccount">访问查询账户</a>
</body>
</html>
控制器代码:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/** * 账户的控制器 */
@Controller("accountController")
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAllAccount")
public String findAllAccount() {
System.out.println("执行了查询账户");
return "success";
}
}
运行结果:
1. 目的:在controller中能成功的调用service对象中的方法。
2. 在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。为了能加载resources下的applicationContext.xml的配置文件所以在web.xml下 在web.xml加:
<!-- 配置 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>
3. 在controller中注入service对象,调用service对象的方法进行测试
package cn.itcast.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.itcast.service.AccountService;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accoutService;
/*** 查询所有的数据 * @return */
@RequestMapping("/findAll")
public String findAll() {
System.out.println("表现层:查询所有账户...");
accoutService.findAll();
return "list";
}
}
方法一: 注意:我们使用代理 dao 的方式来操作持久层,所以此处 Dao 的实现类就是多余的了。
<?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.itheima.dao.IAccountDao">
<!-- 查询所有账户 -->
<select id="findAll" resultType="com.itheima.domain.Account">
select * from account
</select>
<!-- 新增账户 -->
<insert id="save" parameterType="com.itheima.domain.Account">
insert into account(name,money) values(#{
name},#{
money});
</insert>
</mapper>
方法二:在AccountDao接口的方法上添加注解,编写SQL语句
package cn.itcast.dao;
import java.util.List;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import cn.itcast.domain.Account;
public interface AccountDao {
@Insert(value = "insert into account (name,money) values (#{name},#{money})")
public void saveAccount(Account account);
@Select("select * from account")
public List<Account> findAll();
}
<?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>
<properties resource="jdbcConfig.properties"></properties>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="pooled">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/itheima/dao/AccountDao.xml"/>
</mappers>
</configuration>
properties 文件中的内容:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db1
jdbc.username=root
jdbc.password=admin
package com.yg.test;
import com.yg.dao.IAccountDao;
import com.yg.daomain.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 javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Mybatistest {
@Test
public void mybatistest() throws Exception {
//1 加载配置文件
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 创建工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
//3 创建sqlSession对象
SqlSession session = factory.openSession();
//4 获取代理对象
IAccountDao dao = session.getMapper(IAccountDao.class);
//5 调用查询方法
List<Account> accounts = dao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
//6 释放资源
session.close();
inputStream.close();
}
}
整合思路:
把 mybatis 配置文件(SqlMapConfig.xml)中内容配置到 spring 配置文件中 同时,把 mybatis配置文件的内容清掉。
注意: 由于我们使用的是代理 Dao 的模式,Dao 具体实现类由 MyBatis 使用代理方式创建,所以此时 mybatis 配置文件不能删。 当我们整合 spring 和 mybatis 时,mybatis 创建的 Mapper.xml 文件名必须和 Dao 接口文件名一致
<!-- 加载配置文件 --> <context:property-placeholder location="classpath:jdbcConfig.properties"/>
<!-- 配置 MyBatis 的 Session 工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载 mybatis 的全局配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置扫描的dao包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yg.dao"/>
</bean>
<!--配置事务管理器-->
<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="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置aop-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.yg.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
package com.yg.dao;
import com.yg.daomain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface IAccountDao {
@Insert(value="insert into account (name,money) values (#{name},#{money})")
public void saveAccount(Account account);
@Select("select * from account")
public List<Account> findAll();
}
package com.yg.service.impl;
import com.yg.dao.IAccountDao;
import com.yg.daomain.Account;
import com.yg.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public List<Account> findAll() {
System.out.println("业务层查询所有");
return accountDao.findAll();
}
}
package com.yg.test;
import com.yg.dao.IAccountDao;
import com.yg.daomain.Account;
import com.yg.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationContext.xml"})
public class springmybatis {
@Autowired
private IAccountService accountService;
@Test
public void testfindAll() {
List<Account> list = accountService.findAll();
System.out.println(list);
}
@Test
public void testsave() {
Account account= new Account();
account.setName("测试账号");
account.setMoney(1234d);
accountService.saveAccount(account);
}
}
index.jsp:
<%--
Created by IntelliJ IDEA.
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>
<form action="/account/saveAccount" method="post">
账户名称:<input type="text" name="name"><br/>
账户金额:<input type="text" name="money"><br/>
<input type="submit" value="保存">
</form>
</body>
</html>
list.jsp:
<%--
Created by IntelliJ IDEA.
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>客户列表页面</title>
</head>
<body>
<table border="1" width="300px">
<tr>
<th>编号</th>
<th>账户名称</th>
<th>账户金额</th>
</tr>
<c:forEach items="${accounts}" var="account">
<tr>
<td>${
account.id}</td>
<td>${
account.name}</td>
<td>${
account.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
AccountController:
package com.yg.controller;
import com.yg.daomain.Account;
import com.yg.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private IAccountService accountService;
@RequestMapping("/findAll")
public ModelAndView findAll(){
System.out.println("表现层:查询所有账户...");
// 调用service的方法
List<Account> accounts = accountService.findAll();
System.out.println(accounts);
ModelAndView mv = new ModelAndView();
mv.addObject("accounts", accounts);
mv.setViewName("list");
return mv;
}
/** * 保存 * @return */
@RequestMapping("/saveAccount")
public String save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
accountService.saveAccount(account);
return "redirect:findAll";
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/146125.html原文链接:https://javaforall.cn