在互联网行业的项目中尽可能的减少表的管理查询。使用冗余解决表的关联问题。有利于分库分表。
Mybatis的逆向工程。根据数据库表生成java代码。
注意:如果想再次生成代码,必须先将已经生成的代码删除,否则会在原文件中追加。
4 Ssm框架整合
4.1 整合的思路
4.1.1 Dao层
使用mybatis框架。创建SqlMapConfig.xml。
创建一个applicationContext-dao.xml
1、配置数据源
2、需要让spring容器管理SqlsessionFactory,单例存在。
3、把mapper的代理对象放到spring容器中。使用扫描包的方式加载mapper的代理对象。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration>
<configuration>
</configuration>
// applicationContext-dao.xml
<!-- 数据库连接池 -->
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:resource/db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
</bean>
<!-- 配置sqlsessionFactory -->
<bean id="sqlSessionFactory" class="mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
<!-- 配置扫描包,加载mapper代理对象 -->
<bean class="mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.taotao.mapper"></property>
</bean>
4.1.2 Service层
1、事务管理
2、需要把service实现类对象放到spring容器中管理。
// service
<!-- 扫描包加载Service实现类 -->
<context:component-scan base-package="com.taotao.service"></context:component-scan>
// applicationContext-trans.xml
<!-- 事务管理器 -->
<bean id="transactionManager"
class="datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.taotao.service.*.*(..))" />
</aop:config>
// REQUIRED 有事务就在当前事务中,没有事务重新开启一个事务
// SUPPORTS 没有事务不会开启一个事务
4.1.3 表现层
1、配置注解驱动
2、配置视图解析器
3、需要扫描controller
<context:component-scan base-package="com.taotao.controller" />
<mvc:annotation-driven />
<bean
class="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
4.1.4 Web.xml
1、spring容器的配置
2、Springmvc前端控制器的配置
3、Post乱码过滤器
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 解决post乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>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>
<!-- springmvc的前端控制器 -->
<servlet>
<servlet-name>taotao-manager</servlet-name>
<servlet-class>web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>taotao-manager</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
4.2 框架整合
需要把配置文件放到taotao-manager-web工程下。因为此工程为war工程,其他的工程只是一个jar包。
/:会拦截所有请求包括静态资源。需要在springmvc.xml中添加静态资源的映射。
<!-- 资源映射 -->
<mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
6 测试整合结果
6.1 需求
跟据商品id查询商品信息。
6.2 Sql语句
SELECT * from tb_item WHERE id=536563
6.3 Dao层
可以使用逆向工程生成的mapper文件。
6.4 Service层
接收商品id调用dao查询商品信息。返回商品pojo对象。
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private TbItemMapper itemMapper;
@Override
public TbItem getItemById(long itemId) {
//TbItem item = itemMapper.selectByPrimaryKey(itemId);
//添加查询条件
TbItemExample example = new TbItemExample();
Criteria criteria = example.createCriteria();
criteria.andIdEqualTo(itemId);
List<TbItem> list = itemMapper.selectByExample(example);
if (list != null && list.size() > 0) {
TbItem item = list.get(0);
return item;
}
return null;
}
}
注意:做到这里的时候service没有加注解@Service 导致报错
Error creating bean with name ”
6.5 Controller层
接收页面请求商品id,调用service查询商品信息。直接返回一个json数据。需要使用@ResponseBody注解。
@Controller
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("/item/{itemId}")
@ResponseBody
public TbItem getItemById(@PathVariable Long itemId) {
TbItem tbItem = itemService.getItemById(itemId);
return tbItem;
}
}
注意:这里使用了@PathVariable url映射里是是{变量名}
@PathVariable的url是这样的:http://host:port/…/path/参数值
@RequestMapping(“/bookings/{booking}”)
public String getBooking(@PathVariable Long booking) {
}
报错找不到mapper映射文件
解决方法:
修改taotao-manager-mapper的pom文件
在pom文件中添加如下内容:
<!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
7 使用maven的tomcat插件时debug
8 商品列表的实现
8.1 打开后台管理工程的首页
分析:先写一个controller进行页面跳转展示首页。
@Controller
public class PageController {
/**
* 访问跟项目就可以打开首页 http://localhost:8080/
*/
@RequestMapping("/")
public String showIndex() {
return "index";
}
/**
* 展示其他页面
*/
@RequestMapping("/{page}")
public String showpage(@PathVariable String page) {
return page;
}
}
下面报错
SyntaxError: expected expression, got ‘<’ 原因是后台报错,检查发现
/** 展示其他页面 {page} 前面没有写/ jsp页面里面进行ajax交互找不到hadler */
@RequestMapping("/{page}")
public String showPage(@PathVariable String page) {
return page;
}
测试分页插件
@Test
public void testPageHelper(){
ApplicationContext app = new ClassPathXmlApplicationContext(
"classpath:spring/applicationContext-*.xml");
TbItemMapper itemMapper = app.getBean(TbItemMapper.class);
TbItemExample example = new TbItemExample(); // 不加条件就是查询所有
//分页处理
PageHelper.startPage(1, 10);
List<TbItem> list = itemMapper.selectByExample(example);
// 取商品列表
for (TbItem tbItem : list) {
System.out.println(tbItem.getTitle());
}
//取分页信息
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
System.out.println("共有商品:" + pageInfo.getTotal());
}
8.2 商品列表查询
看list页面
url:’/item/list’
2、请求的参数:http://localhost:8080/item/list?page=1&rows=30 分页信息。(需要看官方的手册)
3、返回值。Json数据。数据格式:
Easyui中datagrid控件要求的数据格式为:
{total:”2”,rows:[{“id”:”1”,”name”,”张三”},{“id”:”2”,”name”,”李四”}]}
封装一个类
接收分页参数,一个是page一个是rows。调用dao查询商品列表。并分页。返回商品列表。
返回一个EasyUIDateGrid支持的数据格式。需要创建一个Pojo。此pojo应该放到taotao-common工程中。
public class EUDataGridResult {
private long total;
private List<?> rows; // 用?号
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<?> getRows() {
return rows;
}
public void setRows(List<?> rows) {
this.rows = rows;
}
}
@Override
public EUDataGridResult getItemList(int page, int rows) {
//查询商品列表
TbItemExample example = new TbItemExample();
//分页处理
PageHelper.startPage(page, rows);
List<TbItem> list = itemMapper.selectByExample(example);
//创建一个返回值对象
EUDataGridResult result = new EUDataGridResult();
result.setRows(list);
//取记录总条数
PageInfo<TbItem> pageInfo = new PageInfo<>(list);
result.setTotal(pageInfo.getTotal());
return result;
}
@RequestMapping("/item/list")
@ResponseBody
public EUDataGridResult getItemList(Integer page, Integer rows) {
EUDataGridResult result = itemService.getItemList(page, rows);
return result;
}
打开页面 ok