主流框架:SSM(Spring、SpringMVC、Mybatis)框架整合
一、搭建环境
(1)创建数据库,导入数据
(2)导入依赖坐标,创建子模块
(3)编写domain实体类,service层和dao层接口
/**
* 帐户实体类
*/
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 +
'}';
}
}
/**
* 帐户dao接口
*/
@Repository
public interface AccountDao {
// 查询所有账户
public List<Account> findAll();
// 保存帐户信息
public void saveAccount(Account account);
}
/**
* service层接口
*/
public interface AccountService {
// 查询所有账户
public List<Account> findAll();
// 保存帐户信息
public void saveAccount(Account account);
}
二、Spring框架
Spring作为ssm整合的基础,通过spring来与其他两个框架分别进行整合。先将三个框架,分别独立运行再整合。先保证Spring框架在web工程中独立运行
第一步:编写spring配置文件并导入约束
由于只希望处理service和dao的注解@,controller不需要Spring框架去处理,有专门的SpringMVC层的注解去处理
<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="cn.itcast" >
<!--配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
第二步:使用注解配置业务层和持久层
service层实现类 和 dao层注解配置
/**
* 账户业务层实现类
*/
@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("业务层:保存帐户..."