SSM框架整合

 最近在学习Spring+SpringMVC+MyBatis的整合。以下是参考网上的资料自己实践操作的详细步骤。

SpringMVC+Spring+MyBatis

1. SSM整合思想
原理:java经典三层架构
整合的关键所在:利用MyBatis-Spring项目(mybatis-spring-1.3.0.jar)使得Spring与Mybatis的整合
2. Spring与Mybatis的如何整合?
1、导入spring库、mybatis-spring-1.3.0.jar(MyBatis-Spring项目)、mybatis-3.4.1.jar
2、配置文件
3.整体结构

SSM框架整合_第1张图片

a、数据源  jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/blog
username=root
password=123456
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000

b.日志配置(log4j.properties),整合了相关的资料,日志信息里面配置日志输出位置,输出格式,,文件大小,指定输出日志目录,强调下输出所有日志,如果换成debug表示输出debug以上级别日志!                                                                        

log4j.rootLogger=INFO,Console,File  
#定义日志输出目的地为控制台  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#可以灵活地指定日志输出格式,下面一行是指定具体的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  
  
#文件大小到达指定尺寸的时候产生一个新的文件  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定输出目录  
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n 

C:spring-mvc.xml配置文件,配置文件包括自动扫描,注解驱动,静态资源映射,包括springmvc的上传文件.....




    
    

    
    
    
    

    
    
        
            
                text/html;charset=UTF-8
            
        
    
    
    
        
            
                 
            
        
    

    
    
        
        
        
        
        
        
        
        
    

    
    
        
        
            
                
                
                
                
            
        
        
            
                
                
            
        
        
    

    
    
        
        
        
    


D;spring-mybatsi.xml 配置文件 包括自动扫描,jdbc配置文件数据源, spring与mybatis整合 简单的事务



    
    

    
    
        
    

    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
    
        
        
        
    

    
    
        
        
    

    
    
        
    


3. 如何spring整合mybatis基础上加事务管理




3、利用逆向工具生成pojo、mapper映射xml和接口,注意:需要在类前面加上@Repository注解

@Repository
public interface IUserDao {

    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}


4、编写一个业务Service,注意:需要在配置扫描并在类前面加@Service注解,依赖IUserDao项前面加@Autowired自动配置bean的注解

//IUserService 实现了基本的增删改查

public interface IUserService {

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    User getUserById(int userId);

    /**
     * 添加用户信息
     * @param user
     */
    int insterUser(User user);

    /**
     * 修改用户信息
     * @param user
     */
    int updateUser(User user);

    /**
     * 删除用户信息
     * @param userId
     */
    int delUser(int userId);
}

Service 实现;

@Service("userService")
public class IUserServiceImpl implements IUserService {

    @Resource
    private IUserDao iUserDao;


    @Override
    public User getUserById(int userId) {
        return iUserDao.selectByPrimaryKey(userId);
    }

    @Transactional
    public int insterUser(User user) {
     return iUserDao.insert(user);
    }

    @Transactional
    public int updateUser(User user) {
        return iUserDao.updateByPrimaryKey(user);
    }

    @Transactional
    public int delUser(int userId) {
        return iUserDao.deleteByPrimaryKey(userId);
    }
}

4、测试用例

MainTest.java

public class MainTest {
    public static void main(String[] args) 
    {
        //获取spring的IOC容器
        ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService=(UserService) ctx.getBean("userService");
        User user=new User();
        user.setName("小老弟");
        user.setAge(56);
        user.setSex("男");
        userService.insertUser(user);
    }
}


4. 整合Spring+mybatis+springmvc框架 图解如下:

 

(1)ContextLoaderListener:上下文监听器,会生成上下文的root WebApplication(父IOC容器)

a、配置业务层的bean
b、数据源
c、事务管理
d、dao层的bean、与mybatis整合
(2)DispatcherServlet:前端控制器
    根据springmvc-config.xml生成WebApplication(子ioc容器)
a、配置表现层的bean
b、springmvc相关的核心组件
web.xml

  
  
    Archetype Created Web Application  
      
      
        contextConfigLocation  
        classpath:spring-mybatis.xml  
      
      
      
        encodingFilter  
        org.springframework.web.filter.CharacterEncodingFilter  
        true  
          
            encoding  
            UTF-8  
          
      
      
        encodingFilter  
        /*  
      
      
      
        org.springframework.web.context.ContextLoaderListener  
      
      
      
        org.springframework.web.util.IntrospectorCleanupListener  
      
  
      
      
        SpringMVC  
        org.springframework.web.servlet.DispatcherServlet  
          
            contextConfigLocation  
            classpath:spring-mvc.xml  
          
        1  
        true  
      
      
        SpringMVC  
          
        /  
      
      
        /index.jsp  
      
  
  


4.添加springmvc文件上传功能


    
        
        
        
        
        
        
        
        
    

   

 //文件上传、
    @RequestMapping(value = "/upload")
    public String showUploadPage() {
        return "user_admin/file";
    }

    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String doUploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            log.info("Process file:{}", file.getOriginalFilename());
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File("D:\\", System.currentTimeMillis() + file.getOriginalFilename()));
        return "succes";
    }


    

5. SSM加入分页
分页作用:实现按区域查询数据
分页的主要参数:
1、当前页:    pageindex
2、每页显示记录数:    pageSize
3、总记录条数: totalRecordSum(通过count的sql语句获取)
4、总页数: totalPageNum=(totalRecordSum+pageSize-1)/pageSize
5、开始位置:    sqlstartLimitPos =(pageIndex-1)*pageSize
PageModel.java

public class PageModel {
    private int pageIndex;
    private int pageSize=5;
    private int totalRecordSum;
    private int totalPageNum;
    
    public int getPageIndex() {
        this.pageIndex=this.pageIndex<=1?1:this.pageIndex;
        this.pageIndex=this.pageIndex>=getTotalPageNum()?getTotalPageNum():this.pageIndex;
        return pageIndex;
    }
    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getTotalRecordSum() {
        return totalRecordSum;
    }
    public void setTotalRecordSum(int totalRecordSum) {
        this.totalRecordSum = totalRecordSum;
    }
    public int getTotalPageNum() {
        if(getTotalRecordSum()==0) {
            return 0;
        }
        this.totalPageNum = this.totalRecordSum%this.pageSize==0?this.totalRecordSum/this.pageSize:                                                            (this.totalRecordSum/this.pageSize)+1;
        return totalPageNum;
    }
    public int getStartLimitPos() {
        return (getPageIndex()-1)*getPageSize();
    }
}

编写查询总记录sql定制方法

public class PageModel {
    private int pageIndex;
    private int pageSize=5;
    private int totalRecordSum;
    private int totalPageNum;
    
    public int getPageIndex() {
        this.pageIndex=this.pageIndex<=1?1:this.pageIndex;
        this.pageIndex=this.pageIndex>=getTotalPageNum()?getTotalPageNum():this.pageIndex;
        return pageIndex;
    }
    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public int getTotalRecordSum() {
        return totalRecordSum;
    }
    public void setTotalRecordSum(int totalRecordSum) {
        this.totalRecordSum = totalRecordSum;
    }
    public int getTotalPageNum() {
        if(getTotalRecordSum()==0) {
            return 0;
        }
        this.totalPageNum = this.totalRecordSum%this.pageSize==0?this.totalRecordSum/this.pageSize:                                                            (this.totalRecordSum/this.pageSize)+1;
        return totalPageNum;
    }
    public int getStartLimitPos() {
        return (getPageIndex()-1)*getPageSize();
    }
}

针对mysql的数据库的区域查询
select * from  tb_book where xxxx limit 开始位置,记录条数

整合 SSM肯定不止这点东西,整合只是想对自己使用ssm的熟悉,整合整合过程中会考虑到很多问题,学习的过程中就是不断的去遇到问题解决问题,最好就是写一篇博客,后续还会不断跟新

代码也托管到github ---https://github.com/coreyxuy/SSM

你可能感兴趣的:(Spring)