1.Spring

Needless to say, as one of the best examples of open source, project development is everywhere; The core IOC container, used to load beans (classes in Java) – Spring’s IOC container manages the life cycle of beans so that we don’t have to repeat new operations in our code. Aop, section-oriented programming, is mostly used in Spring for transactions.

2.Spring MVC

Acts on the Web layer and is equivalent to a controller, which, like actions in Struts, handles user requests. It is also more fine-grained than Struts2 and is method-based, whereas Struts is class-based.

3.MyBatis

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can configure and map native information using simple XML or annotations to map interfaces and Java’s POJOs(Plain Old Java Objects) to records in the database. [From: www.mybatis.org/mybatis-3/z…]

Summary of others

  • Hibernate is powerful, database independent, and O/R mapping. If you are proficient in Hibernate and properly packaged, your project’s entire persistence layer code is fairly simple, requires very little code to write, and is very fast and enjoyable to develop.
  • The downside of Hibernate is that there is a high bar to learn, a high bar to master, and a lot of experience and competence in how to design O/R mappings, how to balance performance and object models, and how to use Hibernate well.
  • MYBATIS simple entry, that is to learn and use, provides automatic object binding function of database query, and continued a good SQL experience, for not so high object model requirements of the project, quite perfect.
  • The disadvantage of MYBATIS is that the framework is relatively simple and the function is still missing. Although the data binding code is simplified, the whole underlying database query actually needs to be written by itself, and the workload is relatively large, and it is not easy to adapt to rapid database modification.

    4.SSM framework integration

    This project will take shopping as the background, mainly including commodity information and inventory (because I want to learn about transaction processing), order information. The following steps will cover database creation, project structure description, configuration files, business code, and more.

    4.1 Creating a Database

    Table 1. The goods

    CREATE TABLE `goods` (
    `goods_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'commodity ID',
    `goodsname` varchar(100) NOT NULL COMMENT 'Trade Name',
    `number` int(11) NOT NULL COMMENT 'Merchandise inventory',
     PRIMARY KEY (`goods_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='List of Goods'Copy the code

    Initialize table data

    INSERT INTO `goods` (`goods_id`, `goodsname`, `number`)
    VALUES (1001, 'SN fleece'15),Copy the code

    Table 2. The order

    CREATE TABLE `orderinfo` (
    `order_id` varchar(20) NOT NULL COMMENT 'Order Number',
    `goods_id` bigint(18) NOT NULL COMMENT 'commodity ID',
    `user_id` bigint(10) NOT NULL COMMENT 'user ID',
    `order_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Order time' ,
     PRIMARY KEY (`order_id`),
     INDEX `idx_order_id` (`order_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Order sheet'Copy the code

    OK, now that the table structure and initialization data are built, let’s talk about the mavan-based project structure.

    Description of project Structure

    Since the project uses Maven to manage jar packages, let’s first post the configuration of POM.xml

  • XML < span style = “max-width: 100%; clear: both; min-height: 1em; This case will be based on the principle of “need to use”, to avoid all kinds of chaotic dependence on the Internet are thrown in, resulting in a waste of resources and interference with reading.

    <dependencies> <! GroupId > <artifactId>junit</artifactId> <version>4.11</version> </dependency> <! Slf4j --> <dependency> <groupId>ch.qos. Logback </groupId> <artifactId>logback-classic</artifactId> The < version > 1.1.1 < / version > < / dependency > <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.37 < / version > < scope > runtime < / scope > < / dependency > <! --> <dependency> <groupId> c3P0 </artifactId> c3P0 </artifactId> <version>0.9.1.2</version> </dependency> <! MyBatis </groupId> <artifactId> MyBatis </artifactId> < version > 3.3.0 < / version > < / dependency > < the dependency > < groupId > org. Mybatis < / groupId > < artifactId > mybatis - spring < / artifactId > < version > 1.2.3 < / version > < / dependency > <! GroupId > <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <groupId> JSTL </artifactId> JSTL </artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> < version > 2.5.4 < / version > < / dependency > < the dependency > < groupId > javax.mail. Servlet < / groupId > < artifactId > javax.mail. The servlet API - < / artifactId > < version > 3.1.0 < / version > < / dependency > <! -- 5.Spring --> <! -- 5.1 Spring Core: core bean context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> < version > 4.1.7. RELEASE < / version > < / dependency > < the dependency > < groupId > org. Springframework < / groupId > < artifactId > spring - beans < / artifactId > < version > 4.1.7. RELEASE < / version > < / dependency > < the dependency > < the groupId > org. Springframework < / groupId > < artifactId > spring - the context < / artifactId > < version > 4.1.7. RELEASE < / version > </dependency> <! -- 5.2 Spring JDBC dependencies, Transaction dependency --> <dependency> <groupId>org. springFramework </groupId> <artifactId> Spring - JDBC </artifactId> < version > 4.1.7. RELEASE < / version > < / dependency > < the dependency > < groupId > org. Springframework < / groupId > The < artifactId > spring - tx < / artifactId > < version > 4.1.7. RELEASE < / version > < / dependency > <! -- 5.3 Spring Web dependency> <dependency> <groupId>org. springFramework </groupId> <artifactId> Spring -web</artifactId> < version > 4.1.7. RELEASE < / version > < / dependency > < the dependency > < groupId > org. Springframework < / groupId > The < artifactId > spring - webmvc < / artifactId > < version > 4.1.7. RELEASE < / version > < / dependency > <! 5.4 the Spring -test--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> The < version > 4.1.7. RELEASE < / version > < / dependency > <! Clients </groupId> <artifactId> Jedis </artifactId> < version > 2.7.3 < / version > < / dependency > < the dependency > < groupId > com. Dyuproject. Protostuff < / groupId > < artifactId > protostuff - core < / artifactId > < version > 1.0.8 < / version > < / dependency > < the dependency > < the groupId > com. Dyuproject. Protostuff < / groupId > < artifactId > protostuff - runtime < / artifactId > < version > 1.0.8 < / version > </dependency> <! --> <dependency> <groupId> Commons -collections</groupId> <artifactId> The < version > 3.2 < / version > < / dependency > < / dependencies >Copy the code

    * Project structure diagram



SRC /test/ Java: Test class for junit

















The configuration file

  • jdbc.properties

    jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://serverName:port/dbname? useUnicode=true&characterEncoding=utf8 jdbc.username=[jdbc.password] jdbc.password=[Jdbc.password]Copy the code
    • logback.xml

      Console output is used directly here, and can be configured according to specific requirements in a production environment.
      <? xml version="1.0" encoding="UTF-8"? > <configuration debug="true">
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
         <encoder>
             <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
         </encoder>
      </appender>
      <root level="debug">
         <appender-ref ref="STDOUT" />
      </root>
      </configuration>Copy the code
    • Mybatis -config mybatis-config is used to configure the MyBaties global configuration file. You can configure some class aliases, primary key auto-increment, and camel name rules.

      <configuration> <! -- Configure global properties --> < Settings > <! GetGeneratedKeys = <setting name="useGeneratedKeys" value="true"/ > <! -- Replace column names with column aliasestrue -->
         <setting name="useColumnLabel" value="true"/ > <! Table{create_time} -> Entity{createTime} --> <setting name="mapUnderscoreToCamelCase" value="true" />
      </settings>
      </configuration>Copy the code
    • To get a clearer picture of what spring components do, the data source configuration, transaction configuration, and view resolver configuration are separated here. Spring-dao.xml is the specific process of spring configuration and integration of Mybatis, including: 1. Import the database configuration file. 2. Configure the data source [database connection pool]. 3. Configure the scan Dao interface package, dynamically implement the Dao interface, and inject it into the Spring container

      <! -- 1. Configure the properties of the database related parameter:${url} -->
      <context:property-placeholder location="classpath:jdbc.properties"/ > <! -- 2. Database connection pool --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <! -- Configure connection pool properties --> <property name="driverClass" value="${jdbc.driver}" />
         <property name="jdbcUrl" value="${jdbc.url}" />
         <property name="user" value="${jdbc.username}" />
         <property name="password" value="${jdbc.password}"/ > <! -- c3P0 connection pool private property --> <property name="maxPoolSize" value="30" />
         <property name="minPoolSize" value="10"/ > <! --> <property name="autoCommitOnClose" value="false"/ > <! --> <property name="checkoutTimeout" value="10000"/ > <! -- Retry times when retrieving connection failures --> <property name="acquireRetryAttempts" value="2"/> </bean> <! SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <! -- Inject database connection pool --> <property name="dataSource" ref="dataSource"/ > <! -- Configure the MyBaties global configuration file :mybatis-config. XML --> <property name="configLocation" value="classpath:mybatis-config.xml"/ > <! -- Scan entity package using alias --> <property name="typeAliasesPackage" value="com.glmapper.framerwork.entity"/ > <! --> <property name="mapperLocations" value="com.glmapper.framerwork.mapper/*.xml"/> </bean> <! 4. Configure the scan Dao interface package, dynamically implement the Dao interface, inject into the Spring container --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <! SqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/ > <! <property name="basePackage" value="com.glmapper.framerwork.dao" />
      </bean>Copy the code
    • spring-service

      In real development, transactions are typically operated at the Service layer. Therefore, a separate spring-service.xml is used for transaction-related configuration
      <! <context:component-scan base-package= -- <context:component-scan base-package="com.glmapper.framerwork.service"/ > <! -- Configure transaction manager --> <bean id="transactionManager"
         class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <! -- Inject database connection pool --> <property name="dataSource" ref="dataSource"/> </bean> <! <tx:annotation-driven transaction-Manager ="transactionManager" />Copy the code
    • Spring-web. XML configures SpringMVC; It should be noted that json2Map parsing is usually configured during actual development. Do not use here will not be posted, readers can search online.

      <! -- 1. Enable SpringMVC annotation mode --> < MVC :annotation-driven /> <! -- 2. Static resource default servlet configuration (1) add static resource processing: JS, CSS, images, etc. (2) allow use"/"< MVC :default-servlet-handler/> <! -- 3. Configure ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
          <property name="prefix" value="/WEB-INF/jsp/" />
          <property name="suffix" value=".jsp"/> </bean> <! --> <context:component-scan base-package="com.glmapper.framerwork.web" />Copy the code
    • web.xml
      <! -- encodingFilter --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <! - Spring listener - > < listener > < listener - class > org. Springframework. Web. Context. ContextLoaderListener < / listener - class > </listener> <! -- Prevent Spring memory overflow listener --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <! <servlet> <servlet-name> MVC -dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! Mybatis -> spring- > springMVC -> spring-dao.xml,spring-service. XML,spring-web. XML <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <! -- Matches all requests by default --> <url-pattern>/</url-pattern> </servlet-mapping>Copy the code

      At this point, all the configuration files are finished, and the code is now ready

      Business code

      Mapper: mapper: mapper: mapper: mapper: MAPper

    • Entity class: includes goods and orders

Commodity type

/** * public class Goods {private long goodsId; // Private String goodsName; // private int number; Public long public longgetGoodsId() {
        return goodsId;
    }
    public void setGoodsId(long goodsId) {
        this.goodsId = goodsId;
    }
    public String getGoodsName() {
        return goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) { this.number = number; }}Copy the code

Order class

@author glmapper ** / public class OrderInfo {private String orderId; // Order ID private long goodsId; Private long userId; // user ID private Date orderTime; // Order time public StringgetOrderId() {
        return orderId;
    }
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
    public long getGoodsId() {
        return goodsId;
    }
    public void setGoodsId(long goodsId) {
        this.goodsId = goodsId;
    }
    public long getUserId() {
        return userId;
    }
    public void setUserId(long userId) {
        this.userId = userId;
    }
    public Date getOrderTime() {
        return orderTime;
    }
    public void setOrderTime(Date orderTime) { this.orderTime = orderTime; }}Copy the code
  • Commodity dao
Public interface GoodsDao {/** ** Query information about an item by ID ** @param ID * @return*/ Goods queryById(long id); /** ** Query all commodity information ** @param offset Query start location * @paramlimitQuery the number of entries * @return
     */
    List<Goods> queryAll(@Param("offset") int offset, @Param("limit") int limit); /** ** Reduce inventory ** @param bookId * @returnIf the number of affected rows is >1, it indicates the number of updated record rows */ int reduceNumber(long goodsId); }Copy the code
  • Order the dao

    Public interface OrderInfoDao {/** ** Insert order record ** @param OrderInfo OrderInfo * @return*/ int insertOrderInfo(OrderInfo OrderInfo); /** * return the order entity * @param orderId * @return
       */
      OrderInfo queryByOrderId(String orderId);
    }Copy the code
  • OrderService interface orderService

    @Service("orderService")
    public class OrderServiceImpl implements OrderService {
      //logPrivate Logger Logger = LoggerFactory.getLogger(OrderServiceImpl. Class); @autoWired Private GoodsDao GoodsDao; @Autowired private OrderInfoDao orderInfoDao; @Override public Goods getById(long goodsId) { // TODO Auto-generated method stubreturn goodsDao.queryById(goodsId);
      }
    
      @Override
      public List<Goods> getList(int offset,int limit) {
          // TODO Auto-generated method stub
          return goodsDao.queryAll(offset, limit); } @override @transactional public OrderInfo buyGoods(long goodsId, long userId) { // Reduce inventory int update = goodsDao.reducenumber (goodsId);if(update <= 0) {throw new NoNumberException("no number");
              } elseOrderInfo OrderInfo =new OrderInfo(); orderInfo.setGoodsId(goodsId); orderInfo.setUserId(userId); orderInfo.setOrderTime(new Date()); String orderId=getRandomOrderId(goodsId); orderInfo.setOrderId(orderId); int insert = orderInfoDao.insertOrderInfo(orderInfo);if(insert <= 0) {throw new repeattException (insert <= 0)"repeat appoint");
                  } else{// The reservation succeededreturnorderInfo; }}} catch (Exception e) {// The specific return message logger.error("Order failed");
          } 
          return null;
      }
    
      private String getRandomOrderId(long goodsId) {
          SimpleDateFormat dateFormater = new SimpleDateFormat("yyyyMMddhhmmss");
          String prefix=dateFormater.format(new Date());
          String goodsIdStr=goodsId+"";
          String temp="";
          for (int i = 0; i < 6; i++) {
              Random random=new Random(goodsIdStr.length()-1);
              temp+=goodsIdStr.charAt(random.nextInt());
          }
          returnprefix+temp; }}Copy the code

    OK, so far all core code and configuration files are listed; This article is intended to sort out some points in my study, SSM framework in the actual application development will also have a lot of other open source technologies, such as: Quartz, Redis, etc. The current example of this article is an empty shell for reference.