Integração da estrutura do SSM
1. Prepare
2. Crie um projeto Maven
3. Importar coordenadas do Maven
Referência: arquivo material / configuration / pom.xml
4. Gravar classe de entidade
public class Account {
private int id;
private String name;
private double money;
//省略getter和setter方法
}
5. Interface do Write Mapper
public interface AccountMapper {
//保存账户数据
void save(Account account);
//查询账户数据
List<Account> findAll();
}
6. Interface de Serviço de Gravação
public interface AccountService {
void save(Account account); //保存账户数据
List<Account> findAll(); //查询账户数据
}
7. Implementação da interface Write Service
@Service("accountService")
public class AccountServiceImpl implements AccountService {
public void save(Account account) {
SqlSession sqlSession = MyBatisUtils.openSession();
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
accountMapper.save(account);
sqlSession.commit();
sqlSession.close();
}
public List<Account> findAll() {
SqlSession sqlSession = MyBatisUtils.openSession();
AccountMapper accountMapper = sqlSession.getMapper(AccountMapper.class);
return accountMapper.findAll();
}
}
8. Controlador de gravação
@Controller
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/save")
@ResponseBody
public String save(Account account){
accountService.save(account);
return "save success";
}
@RequestMapping("/findAll")
public ModelAndView findAll(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("accountList");
modelAndView.addObject("accountList",accountService.findAll());
return modelAndView;
}
}
9. Escrever Adicionar Página
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>保存账户信息表单</h1>
<form action="${pageContext.request.contextPath}/save.action" method="post">
用户名称<input type="text" name="name"><br/>
账户金额<input type="text" name="money"><br/>
<input type="submit" value="保存"><br/>
</form>
</body>
</html>
10. Escreva uma página de lista
<table border="1">
<tr>
<th>账户id</th>
<th>账户名称</th>
<th>账户金额</th>
</tr>
<c:forEach items="${accountList}" var="account">
<tr>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
</tr>
</c:forEach>
</table>
11. Escreva o arquivo de configuração correspondente (diretório de referência do arquivo: arquivo de material / configuração)
• Arquivo de configuração do Spring: applicationContext.xml
• Arquivo de configuração SprngMVC: spring-mvc.xml
• Arquivo de mapeamento MyBatis: AccountMapper.xml
• Arquivo principal do MyBatis : sqlMapConfig.xml
• Arquivo de informações de conexão com o banco de dados: jdbc.properties
• Conteúdo Web.xml: web.xml
• Arquivo de log: [log4j.xml] (
12. Teste de adição de uma conta
13. Lista de contas de teste
1.2 Integração de primavera MyBatis
1. Ideias de integração
2. Configure SqlSessionFactory no contêiner Spring
<!--加载jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置MyBatis的SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>
3. Examine o Mapper e deixe o contêiner Spring gerar a classe de implementação do Mapper
<!--配置Mapper扫描-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ittest.mapper"/>
</bean>
4. Configure o controle declarativo da transação
<!--配置声明式事务控制-->
<bean id="transacionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="transacionManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.ittest.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
5. Modifique o código da classe de implementação do Serviço
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
public void save(Account account) {
accountMapper.save(account);
}
public List<Account> findAll() {
return accountMapper.findAll();
}
}