SSM整合
需求和步骤分析 :
需求
使用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 ) ;
创建web项目:
编写mybatis在ssm环境中可以单独使用
需求:基于mybatis先来实现对account表的查询:
相关坐标 :
< 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 >
Account实体 :
package com. lagou. domain ;
public class Account {
private Integer id;
private String name;
private Double 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;
}
}
AccountDao接口:
package com. lagou. dao ;
import com. lagou. domain. Account ;
import java. util. List ;
public interface AccountDao {
public List < Account > findAll ( ) ;
}
AccountDao.xml映射(记得与接口目录相同,且在资源文件夹里面) :
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
< mapper namespace = " com.lagou.dao.AccountDao" >
< select id = " findAll" resultType = " com.lagou.domain.Account" >
select * from account
select >
mapper >
mybatis核心配置文件:
jdbc.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db?characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456
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.lagou.domain" />
typeAliases >
< environments default = " dev" >
< environment id = " dev" >
< 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>
< package name = " com.lagou.dao" />
mappers >
configuration >
测试代码:
package com. lagou. text ;
import com. lagou. dao. AccountDao ;
import com. lagou. 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. File ;
import java. io. IOException ;
import java. io. InputStream ;
import java. util. List ;
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 ( ) ;
}
}
编写spring在ssm环境中可以单独使用:
相关坐标:
< 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 >
AccountService接口:
package com. lagou. service ;
import com. lagou. domain. Account ;
import java. util. List ;
public interface AccountService {
public List < Account > findAll ( ) ;
}
AccountServiceImpl实现 :
package com. lagou. service. imp ;
import com. lagou. domain. Account ;
import com. lagou. service. AccountService ;
import java. util. List ;
@Service
public class AccountServiceImpl implements AccountService {
@Override
public List < Account > findAll ( ) {
System . out. println ( "findAll执行了...." ) ;
return null ;
}
}
spring核心配置文件:
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.lagou.service" > context: component-scan>
beans >
测试代码:
package com. lagou. text ;
import com. lagou. service. AccountService ;
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 ;
@RunWith ( SpringJUnit4ClassRunner . class )
@ContextConfiguration ( "classpath:applicationContext.xml" )
public class SpringText {
@Autowired
private AccountService accountService;
@Test
public void testSpring ( ) {
accountService. findAll ( ) ;
}
}
spring整合mybatis:
整合思想:
将mybatis接口代理对象的创建权交给spring管理,我们就可以把dao的代理对象注入到service中
此时也就完成了spring与mybatis的整合了
导入整合包:
< dependency>
< groupId> org.mybatisgroupId >
< artifactId> mybatis-springartifactId >
< version> 1.3.1version >
dependency >
spring配置文件管理mybatis
注意:此时可以将mybatis主配置文件删除
< 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.lagou.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 >
< property name = " url" value = " ${jdbc.url}" > property >
< property name = " username" value = " ${jdbc.username}" > property >
< property name = " password" value = " ${jdbc.password}" > property >
bean >
< bean id = " sessionFactory" class = " org.mybatis.spring.SqlSessionFactoryBean" >
< property name = " dataSource" ref = " dataSource" > property >
< property name = " typeAliasesPackage" value = " com.lagou.domain" > property >
bean >
< bean class = " org.mybatis.spring.mapper.MapperScannerConfigurer" >
< property name = " basePackage" value = " com.lagou.dao" > property >
bean >
beans >
修改AccountServiceImpl :
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List < Account > findAll ( ) {
List < Account > all = accountDao. findAll ( ) ;
return all;
}
}
编写springMVC在ssm环境中可以单独使用:
需求:访问到controller里面的方法查询所有账户,并跳转到list.jsp页面进行列表展示
相关坐标 :
< 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://pan.baidu.com/s/15MMY53jP7zxZaLb6pqFK5w
提取码:alsk
前端控制器DispathcerServlet:
< 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 >
springMVC核心配置文件 :
< 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.lagou.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 >
AccountController和部分list.jsp:
package com. lagou. controller ;
import com. lagou. domain. Account ;
import com. lagou. service. AccountService ;
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 java. util. ArrayList ;
import java. util. List ;
@Controller
@RequestMapping ( "/account" )
public class AccountController {
@RequestMapping ( "/findAll" )
public String findAll ( Model model) {
ArrayList < Account > list = new ArrayList < > ( ) ;
Account account = new Account ( ) ;
account. setId ( 1 ) ;
account. setName ( "张三" ) ;
account. setMoney ( 1000d ) ;
Account account2 = new Account ( ) ;
account2. setId ( 2 ) ;
account2. setName ( "李四" ) ;
account2. setMoney ( 1000d ) ;
list. add ( account) ;
list. add ( account2) ;
model. addAttribute ( "list" , list) ;
return "list" ;
}
}
${account.id}
${account.name}
${account.money}
修改 删除
spring整合springMVC:
整合思想:
spring和springMVC其实根本就不用整合,本来就是一家
但是我们需要做到spring和web容器整合,让web容器启动的时候自动加载spring配置文件
web容器销毁的时候spring的ioc容器也销毁
spring和web容器整合:
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 >
在前面66章的博客最后有对应介绍
修改AccountController :
package com. lagou. controller ;
import com. lagou. domain. Account ;
import com. lagou. service. AccountService ;
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 java. util. ArrayList ;
import java. util. List ;
@Controller
@RequestMapping ( "/account" )
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping ( "/findAll" )
public String findAll ( Model model) {
List < Account > all = accountService. findAll ( ) ;
model. addAttribute ( "list" , all) ;
return "list" ;
}
}
为什么使用监听器呢,一般的,我们要在一个类里面进行使用IOC的实例
那么基本需要进行读取配置(文件或者类),得到IOC容器
spring配置声明式事务:
spring配置文件加入声明式事务,以及去修改对应类 :
< bean id = " dataSourceTransactionManager"
class = " org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name = " dataSource" ref = " dataSource" > property >
bean >
< tx: annotation-driven> tx: annotation-driven>
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
}
部分add.jsp:
添加方法到AccountController:
@RequestMapping ( "/save" )
public String save ( Account account) {
accountService. save ( account) ;
return "redirect:/account/findAll" ;
}
添加方法到AccountService接口和实现类:
void save ( Account account) ;
@Override
public void save ( Account account) {
accountDao. save ( account) ;
}
添加方法到AccountDao:
void save ( Account account) ;
添加对应AccountDao.xml映射 :
< insert id = " save" parameterType = " account" >
insert into account(name,money) values(#{name},#{money})
insert >
最后注意:EL表达式输出null时,一般会解析成"“(判断变化的,即如果是null,那么就赋值”"空串),也就是空串
修改操作:
数据回显:
添加方法到AccountController :
@RequestMapping ( "/findById" )
public String findById ( Integer id, Model model) {
Account account = accountService. findById ( id) ;
model. addAttribute ( "account" , account) ;
return "update" ;
}
添加方法到AccountService接口和实现类 :
Account findById ( Integer id) ;
@Override
public Account findById ( Integer id) {
return accountDao. findById ( id) ;
}
添加方法到AccountDao接口:
Account findById ( Integer id) ;
添加对应AccountDao.xml映射 :
< select id = " findById" parameterType = " int" resultType = " account" >
select * from account where id = #{id}
select >
部分update.jsp:
账户更新:
添加方法到AccountController :
@RequestMapping ( "/update" )
public String update ( Account account) {
accountService. update ( account) ;
return "redirect:/account/findAll" ;
}
添加方法到AccountService接口和实现类 :
void update ( Account account) ;
@Override
public void update ( Account account) {
accountDao. update ( account) ;
}
添加方法到AccountDao接口:
void update ( Account account) ;
添加对应AccountDao.xml映射 :
< update id = " update" parameterType = " account" >
update account set name = #{name},money = #{money} where id = #{id}
update >
批量删除:
部分list.jsp:
<%--实现全选全不选效果--%>
添加方法到AccountController :
@RequestMapping ( "/deleteBatch" )
public String deleteBatch ( Integer [ ] ids) {
accountService. deleteBatch ( ids) ;
return "redirect:/account/findAll" ;
}
添加方法到AccountService接口和实现类 :
void deleteBatch ( Integer [ ] ids) ;
@Override
public void deleteBatch ( Integer [ ] ids) {
accountDao. deleteBatch ( ids) ;
}
添加方法到AccountDao接口:
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 >
最后注意:要给数据库表添加备注,可以使用在字段后面加上comment ‘主键’,后面的主键就是备注名
且虽然mysql的int不用设置长度(实际上是补位),如int(3),那么加上1时,隐藏的显示001
但一次性的长度是不能添加超过11的,否则报错
当你传入Date数据时,Java的框架或者方法基本在最后替换时(如占位符)会自动变成对应字符串数
然后进行替换,使得可以执行对应sql语句,当然不同的sql字段得到的显示结果不同
一般的date字段只会显示年月日,当然也可以设置时分秒(如datetime数据库字段类型),则会多出时分秒
最后注意刷新,就可以看到最后的结果了
且Java中日期设置什么格式,对应的字符串基本就要什么格式,否则报错