SSM整合使用

 

SSM全称Spring + SpringMVC + MyBatis,是目前比较主流的Java EE企业级框架,适用于搭建各种大型的企业级应用系统。

直接上demo

首先,引入项目依赖,包括web, mybatis,数据库使用的是MySQL 8.0+

?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mike.boot.ssm</groupId>
    <artifactId>boot-ssm-1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-ssm-1</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

  为了方便开发,这里引入了2个插件,devtools 和lombok的依赖。

devtools 用于热部署,即编辑完自动run起来,但IDE要使用devtools 要做以下的配置

  • settings-build-compiler->勾选build project autoxxx选项

  • shift+alt+ctrl+/ ->registry->勾选compiler.automake.allow.when.app.running

使用lombok则需要安装lombok的插件

 *马赛克地方为测试无关代码

配置application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver  # Driver
    url: jdbc:mysql:///testdb?useSSL=true&serverTimezone=CTT #jdbc:mysql:///testdb?useSSL=true&serverTimezone=CTT
    username: username
    password: passwoord
mybatis:
  configuration:
    map-underscore-to-camel-case: true  # book_id => bookId,book_name=> bookName
  mapper-locations: classpath:mapper/*Mapper.xml # 指定Mapper映射路径
  type-aliases-package: com.mike.boot.ssm.bootssm1.domain #定义别名  

创建实体对象,由于使用了lombok,所以大大简化了getter和setter

mport lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class BookInfo {
    private Integer bookId;
    private String bookName;
    private String bookAuthor;
    private BigDecimal bookPrice;
    private Date bookDate;
}

创建操作接口BookMapper.java并且添加@Mapper注解将class交给spring容器管理。

import com.mike.boot.ssm.bootssm1.domain.BookInfo;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper//将该接口的实体类对象交给springboot容器管理
public interface BookMapper {
    /**
     * 根据ID获取书
     * @param id
     * @return
     */
    BookInfo getBookById(Integer id);

    /**
     * 保存
     * @param bookInfo
     * @return
     */
    int saveBook(BookInfo bookInfo);

    /**
     * 批量插入
     * @param list
     * @return
     */
    int saveBookBatch(List<BookInfo> books);

}

  有了接口,还得配置SQL statement,在resource下创建mapper文件夹专门用来编辑SQL statement xml(BookInfoMapper.xml),为什么是resource/mapper/下呢?因为我们再application.yml添加了配置

mybatis:
mapper-locations: classpath:mapper/*Mapper.xml

  BookInfoMapper.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.mike.boot.ssm.bootssm1.mapper.BookMapper">
    <select id="getBookById" resultType="bookInfo">
        select  book_id,book_name,book_author,book_price,book_date
        from  book
        where book_id=#{id};
    </select>
    <insert id="saveBook" parameterType="bookInfo">
        insert  book(book_name,book_author,book_price,book_date)
        values(#{bookName},#{bookAuthor},#{bookPrice},#{bookDate});
    </insert>

    <insert id="saveBookBatch" parameterType="java.util.List">
        insert  book(book_name,book_author,book_price,book_date)
        values
        <foreach collection="list" item="val"  separator=",">
            (#{val.bookName},#{val.bookAuthor},#{val.bookPrice},#{val.bookDate})
        </foreach>
    </insert>
</mapper>

  注意这里的resultType是因为在application.yml里配置了别名,所以可以这样使用

mybatis:
  type-aliases-package: com.mike.boot.ssm.bootssm1.domain #定义别名

  至此,一个基本的SSM项目搭建完成。添加测试代码,以selectOne为例查看效果

import com.mike.boot.ssm.bootssm1.domain.BookInfo;
import com.mike.boot.ssm.bootssm1.mapper.BookMapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RunWith(SpringRunner.class)
@SpringBootTest
public class BootSsm1ApplicationTests {

    @Resource
    private BookMapper bookMapper;

    @Test
    public void selectOne() {
        BookInfo bookInfo = bookMapper.getBookById(2);
        System.out.println(bookInfo);
    }

    @Test
    public void save() {
        BookInfo bookInfo = new BookInfo();
        bookInfo.setBookName("魔童降世");
        bookInfo.setBookAuthor("佚名");
        bookInfo.setBookPrice(new BigDecimal(40));
        bookInfo.setBookDate(new Date(2019, 07, 26 ));

        bookMapper.saveBook(bookInfo);
    }

    @Test
    public void saveBatch() throws ParseException {
        BookInfo bookInfo = new BookInfo();
        bookInfo.setBookName("魔童降世3");
        bookInfo.setBookAuthor("佚名3");
        bookInfo.setBookPrice(new BigDecimal(40));
        bookInfo.setBookDate(new SimpleDateFormat("yyyy-MM-dd").parse("2019-07-28"));
        List<BookInfo> books= new ArrayList<>();
        books.add(bookInfo);
        books.add(bookInfo);
        int rows=bookMapper.saveBookBatch(books);
        Assert.assertEquals(2,rows);
    }

}

  最后,查看demo结果。

 

posted @ 2023-05-19 08:51  天晴修屋顶  阅读(29)  评论(0编辑  收藏  举报