美文网首页
后端工程创建过程(SSM框架搭建即项目初始化)

后端工程创建过程(SSM框架搭建即项目初始化)

作者: Even会编程 | 来源:发表于2020-02-19 11:43 被阅读0次

    该后端工程的创建、开发过程均使用Intellij IDEA进行

    1. 打开Intellij IDEA创建新的project,使用Spring Initializr创建springboot框架项目,步骤如下;


      创建springboot项目
    填写Group和Artifact,其他默认 选择Web-Spring Web和SQL-Mybatis Framework、MySQL Driver 填写项目名称和项目存储路径,之后项目创建成功

    注:必须开启maven的自动导入,即pom文件自动导入依赖库(在项目创建成功之后会在IDE右下方弹出提醒开启)

    1. 完成mybatis相关的配置;


      创建mybatis-config.xml配置mybatis相关属性,代码如下:
    // mybatis-config.xml
    
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!-- 配置文件的根元素 -->
    <configuration>
        <!--配置全局属性-->
        <settings>
            <!--使用jdbc的getGeneratedKeys获取数据库自增主键值-->
            <setting name="useGeneratedKeys" value="true"/>
            <!--使用列标签替换列别名 默认未true-->
            <setting name="useColumnLabel" value="true" />
            <!--开启驼峰式命名转换:Table{create_time} -> Entity{createTime}-->
            <setting name="mapUnderscoreToCamelCase" value="true" />
        </settings>
    </configuration>
    
    完成spring配置(数据库、端口、配置文件路径等)代码如下:
    // application.properties
    
    #1.项目启动的端口
    server.port=8080
    
    #2.数据库连接参数
    #2.1jdbc驱动,示数据库厂商决定,这是mysql的驱动
    jdbc.driver=com.mysql.cj.jdbc.Driver
    #2.2数据库连接url,包括ip(127.0.0.1)、端口(3306)、数据库名(testdb)
    jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf-8&useSSL=false
    #2.3数据库账号名
    jdbc.username=root
    #2.4数据库密码
    jdbc.password=511359588
    
    #3.Mybatis配置
    #3.1 mybatis配置文件所在路径
    mybatis_config_file=mybatis-config.xml
    #3.2 mapper文件所在路径,这样写可匹配mapper目录下的所有mapper,包括其子目录下的
    mapper_path=/mapper/**/**.xml
    #3.3 entity所在包
    entity_package=com.evenzhu.ssm.entity
    
    完成src路径下文件夹和class文件的创建,涉及代码如下:
    // DataSourceConfiguration
    
    package com.evenzhu.ssm.config.dao;
    
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.beans.PropertyVetoException;
    
    /**
     * 数据库配置类
     */
    @Configuration
    public class DataSourceConfiguration {
    
        @Value("${jdbc.driver}")
        private String jdbcDriver;
        @Value("${jdbc.url}")
        private String jdbcUrl;
        @Value("${jdbc.username}")
        private String jdbcUsername;
        @Value("${jdbc.password}")
        private String jdbcPassword;
    
        @Bean(name = "dataSouce")
        public ComboPooledDataSource createDataSouce() throws PropertyVetoException {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(jdbcDriver);
            dataSource.setJdbcUrl(jdbcUrl);
            dataSource.setUser(jdbcUsername);
            dataSource.setPassword(jdbcPassword);
            //关闭连接后不自动commit
            dataSource.setAutoCommitOnClose(false);
            return dataSource;
        }
    }
    
    // SessionFactoryConfiguration
    
    package com.evenzhu.ssm.config.dao;
    
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    
    import javax.sql.DataSource;
    import java.io.IOException;
    
    /**
     * 数据库sqlSession配置类
     */
    
    @Configuration
    public class SessionFactoryConfiguration {
    
        @Value("${mapper_path}")
        private String mapperPath;
    
        @Value("${mybatis_config_file}")
        private String mybatisConfigFilePath;
    
        @Autowired
        private DataSource dataSouce;
        @Value("${entity_package}")
        private String entityPackage;
    
        @Bean(name="sqlSessionFactory")
        public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
            sqlSessionFactoryBean.setDataSource(dataSouce);
            sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
            return sqlSessionFactoryBean;
        }
    }
    
    // TransactionManagementConfiguration
    
    package com.evenzhu.ssm.config.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    import org.springframework.transaction.annotation.TransactionManagementConfigurer;
    
    import javax.sql.DataSource;
    
    /**
     * 事务配置类,不可缺少,尚未知具体作用
     */
    @Configuration
    @EnableTransactionManagement
    public class TransactionManagementConfiguration implements TransactionManagementConfigurer{
    
        @Autowired
        private DataSource dataSource;
    
        @Override
        public PlatformTransactionManager annotationDrivenTransactionManager() {
            return new DataSourceTransactionManager(dataSource);
        }
    }
    
    // TestController
    
    package com.evenzhu.ssm.controller;
    
    import com.evenzhu.ssm.entity.TestEntity;
    import com.evenzhu.ssm.service.TestService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/demoproject/test")
    public class TestController {
    
        @Autowired
        private TestService testService ;
    
        @RequestMapping(value = "/get/{id}",method = RequestMethod.GET)
        public TestEntity test(@PathVariable Integer id){
            System.out.println("id:" + id);
            return testService.getById(id);
        }
    }
    

    3.运行项目会报错,那是因为项目缺少一些依赖,需要在pom中添加依赖;


    在pom文件中添加第三方库的依赖,代码如下:
        <dependencies>
            ...
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </dependency>
    
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
    

    4.截止到目前已经完成了ssm项目的初步配置,接下来需要完成数据库操作相关的配置和代码;


    创建以上文件夹和文件,涉及代码如下:
    // TestDao.class
    
    package com.evenzhu.ssm.dao;
    
    
    import com.evenzhu.ssm.entity.TestEntity;
    import org.apache.ibatis.annotations.Mapper;
    
    @Mapper
    public interface TestDao {
    
        TestEntity getById(Integer id);
    
    }
    
    
    // TestEntity.class
    
    package com.evenzhu.ssm.entity;
    
    public class TestEntity {
    
        protected Integer id ;
    
        protected String magicId ;
    
        protected String firstName ;
    
        protected String lastName ;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getMagicId() {
            return magicId;
        }
    
        public void setMagicId(String magicId) {
            this.magicId = magicId;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }
    
    // TestService.class
    
    package com.evenzhu.ssm.service;
    
    import com.evenzhu.ssm.dao.TestDao;
    import com.evenzhu.ssm.entity.TestEntity;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class TestService {
    
        @Autowired
        private TestDao testDao ;
    
        public TestEntity getById(Integer id){
            return testDao.getById(id);
        }
    }
    
    
    // TestDaoMapper.xml
     
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.evenzhu.ssm.dao.TestDao">
        <!-- 根据主键查询-->
        <select id="getById" resultType="com.evenzhu.ssm.entity.TestEntity" parameterType="java.lang.Integer" >
            select  *
            from test
            where id = #{id}
        </select>
    </mapper>
    
    数据库及表的创建

    注:数据库配置在application.properties中,表名及SQL配置在
    src/main/resources/mapper/**.xml中,配置信息一定要与数据库实际配置保持一致

    浏览器测试请求成功,完成

    注:篇中涉及的包名com.evenzhu.ssm必须改为读者自己项目的包名

    全篇完,如有问题请评论私聊,我会及时回复并更新文章;

    相关文章

      网友评论

          本文标题:后端工程创建过程(SSM框架搭建即项目初始化)

          本文链接:https://www.haomeiwen.com/subject/xbvofhtx.html