需求
使用ssm框架完成对 account 表的增删改查操作。
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `account`(`id`,`name`,`money`) values (1,'tom',1000), (2,'jerry',1000);
创建步骤可参考这篇文章:https://blog.csdn.net/u012660464/article/details/126652568?spm=1001.2014.3001.5501
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.15version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
public class Account {
private Integer id;
private String name;
private Double money;
public Account() {
}
public Account(int id, String name, double money) {
this.id =id;
this.name = name;
this.money = money;
}
public Account(String name, double money) {
this.name = name;
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + 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;
}
}
public interface AccountDao {
/*
查询所有账户
*/
public List<Account> findAll();
void save(Account account);
Account findById(Integer id);
void update(Account account);
void deleteBatch(Integer[] ids);
}
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zwt.dao.AccountDao">
<select id="findAll" resultType="account">
select * from account
select>
<insert id="save" parameterType="account">
insert into account(name,money) values(#{name},#{money})
insert>
<select id="findById" parameterType="int" resultType="account">
select * from account where id = #{id}
select>
<update id="update" parameterType="account">
update account set name = #{name},money = #{money} where id = #{id}
update>
<delete id="deleteBatch" parameterType="int">
delete from account
<where>
<foreach collection="array" open="id in(" close=")" separator="," item="id">
#{id}
foreach>
where>
delete>
mapper>
注:xml 包名及结构需要和 java 文件一致
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.username=root
jdbc.password=zhangwt
注:一般 resourse 资源目录下,数据库信息需根据自身情况调整
SqlMapConfig.xml
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<typeAliases> <package name="com.zwt.domain"/> typeAliases>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<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>
<package name="com.zwt.dao"/>
mappers>
configuration>
注:一般 resourse 资源目录下
public class MybatisTest {
@Test
public void testMybatis() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountDao mapper = sqlSession.getMapper(AccountDao.class);
List<Account> all = mapper.findAll();
for (Account account : all) {
System.out.println(account);
}
sqlSession.close();
}
}
当前项目结构如下:
运行测试类,可以发现mybatis单独配置成功
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.1.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.13version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.1.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.1.5.RELEASEversion>
dependency>
public interface AccountService {
public List<Account> findAll();
void save(Account account);
Account findById(Integer id);
void update(Account account);
void deleteBatch(Integer[] ids);
}
@Service
public class AccountServiceImpl implements AccountService {
/*
测试spring在ssm环境中的单独使用
*/
public List<Account> findAll() {
System.out.println("findAll执行了....");
return null;
}
public void save(Account account) {
}
public Account findById(Integer id) {
return null;
}
public void update(Account account) {
}
public void deleteBatch(Integer[] ids) {
}
}
applicationContext.xml
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.zwt.service">context:component-scan>
beans>
//替换运行器,指定当前Junit的环境为Spring环境
@RunWith(SpringJUnit4ClassRunner.class)
//加载核心配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTest {
@Autowired
private AccountService accountService;
@Test
public void testSpring(){
List<Account> all = accountService.findAll();
for (Account account : all) {
System.out.println(account);
}
}
}
将mybatis接口代理对象的创建权交给spring管理,我们就可以把dao的代理对象注入到service中,此时也就完成了spring与mybatis的整合了。
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
注意:此时可以将mybatis主配置文件 SqlMapConfig.xml 删除。
applicationContext.xml
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.zwt.service">context:component-scan>
<context:property-placeholder location="classpath:jdbc.properties">context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="typeAliasesPackage" value="com.zwt.domain">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.zwt.dao">property>
bean>
beans>
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
/*
测试spring在ssm环境中的单独使用
*/
public List<Account> findAll() {
return accountDao.findAll();
}
public void save(Account account) {
}
public Account findById(Integer id) {
return null;
}
public void update(Account account) {
}
public void deleteBatch(Integer[] ids) {
}
}
需求:访问到controller里面的方法查询所有账户,并跳转到list.jsp页面进行列表展示
pom.xml
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.1.5.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
相关页面素材资源已上传,点击链接可下载,https://download.csdn.net/download/u012660464/86507398
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>2load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
@Controller
@RequestMapping("/account")
public class AccountController {
/*
查询所有用户
*/
@RequestMapping("/findAll")
public String findAll(Model model){
List<Account> list = new ArrayList<>();
list.add(new Account(1,"张三",1000d));
list.add(new Account(2,"李四",1000d));
model.addAttribute("list", list);
return "list";
}
}
list.jsp
<c:forEach items="${list}" var="account">
<tr>
<td>
<input type="checkbox" name="ids" value="${account.id}">
</td>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
<td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/account/findById?id=${account.id}">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td>
</tr>
</c:forEach>
spring-mvc.xml
<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">
<context:component-scan base-package="com.zwt.controller">context:component-scan>
<mvc:annotation-driven>mvc:annotation-driven>
<bean id="resourceViewResolve" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:default-servlet-handler>mvc:default-servlet-handler>
beans>
配置tomcat
把当前工程,部署到tomcat上
选择application sever
create configuration
点击Apply 和 ok
启动tomcat
在浏览器访问:http://localhost:8080/ssmWeb/account/findAll
spring和springMVC其实根本就不用整合,本来就是一家。
但是我们需要做到spring和web容器整合,让web容器启动的时候自动加载spring配置文件,web容器销毁的时候spring的ioc容器也销毁。
ContextLoaderListener加载
可以使用spring-web包中的ContextLoaderListener监听器,可以监听servletContext容器的创建和销毁,来同时创建或销毁IOC容器。
web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
/*
查询所有用户
*/
@RequestMapping("/findAll")
public String findAll(Model model){
List<Account> list = accountService.findAll();
model.addAttribute("list", list);
return "list";
}
}
启动tomcat,使用浏览器访问 http://localhost:8080/ssmWeb/account/findAll
applicationContext.xml
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:annotation-driven/>
AccountServiceImpl 类添加 @Transactional 注解
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
//...
}
<form action="${pageContext.request.contextPath}/account/save" method="post">
<div class="form-group">
<label for="name">姓名:label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
div>
<div class="form-group">
<label for="money">余额:label>
<input type="text" class="form-control" id="money" name="money" placeholder="请输入余额">
div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" />
<input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
div>
form>
修改save方法
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/save")
public String save(Account account){
accountService.save(account);
// 跳转到findAll方法重新查询一次数据库进行数据的遍历展示
return "redirect:/account/findAll";
}
}
AccountService.java
public interface AccountService {
void save(Account account);
}
AccountServiceImpl.java
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
//需要用到AccountDao的代理对象
@Autowired
private AccountDao accountDao;
/*
账户添加
*/
@Override
public void save(Account account) {
accountDao.save(account);
}
}
AccountDao.java
void save(Account account);
<insert id="save" parameterType="account">
insert into account(name,money) values(#{name},#{money})
insert>
启动tomcat,使用浏览器访问 http://localhost:8080/ssmWeb/add.jsp
至此,SSM框架整合已经完成了!
为了以后方便,我们再把修改和删除操作完善,做成一个Demo,方便后续参考。
/*
根据id查询账户信息,完成账户回显
*/
@RequestMapping("/findById")
public String findById(Integer id,Model model){
Account account = accountService.findById(id);
//存到model中
model.addAttribute("account",account);
//视图跳转
return "update";
}
AccountService.java
Account findById(Integer id);
AccountServiceImpl.java
@Override
public Account findById(Integer id) {
return accountDao.findById(id);
}
Account findById(Integer id);
<!--根据ID查询账户信息 Account findById(Integer id);-->
<select id="findById" parameterType="int" resultType="account">
select * from account where id = #{id}
</select>
<form action="${pageContext.request.contextPath}/account/update" method="post">
<input type="hidden" name="id" value="${account.id}">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" value="${account.name}" placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="money">余额:</label>
<input type="text" class="form-control" id="money" name="money" value="${account.money}" placeholder="请输入余额">
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" />
<input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
</div>
</form>
/*
更新账户
*/
@RequestMapping("/update")
public String update(Account account){
accountService.update(account);
return "redirect:/account/findAll";
}
AccountService.java
void update(Account account);
AccountServiceImpl.java
@Override
public void update(Account account) {
accountDao.update(account);
}
AccountDao.java
void update(Account account);
AccountDao.xml
<update id="update" parameterType="Account">
update account set name = #{name},money = #{money} where id = #{id} update>
启动tomcat,使用浏览器访问 http://localhost:8080/ssmWeb/account/findAll
<script>
/*给删除选中按钮绑定点击事件*/
$('#deleteBatchBtn').click(function () {
if(confirm('您确定要删除吗')){
if($('input[name=ids]:checked').length > 0){
/*提交表单*/
$('#deleteBatchForm').submit();
}
}else {
alert('想啥呢,没事瞎操作啥')
}
})
script>
/*
批量删除
*/
@RequestMapping("/deleteBatch")
public String deleteBatch(Integer[] ids){
accountService.deleteBatch(ids);
return "redirect:/account/findAll";
}
AccountService.java
void deleteBatch(Integer[] ids);
AccountServiceImpl.java
@Override
public void deleteBatch(Integer[] ids) {
accountDao.deleteBatch(ids);
}
AccountDao.java
void deleteBatch(Integer[] ids);
AccountDao.xml
<delete id="deleteBatch" parameterType="int">
delete from account
<where>
<foreach collection="array" open="id in(" close=")" separator="," item="id">
#{id}
foreach>
where>
delete>
启动tomcat,使用浏览器访问 http://localhost:8080/ssmWeb/account/findAll
至此,整个Demo工程完成,我已上传完整版的源码,可直接下载使用,下载链接:
https://download.csdn.net/download/u012660464/86507494