基于springboot实现SSM整合
阅读原文时间:2023年07月08日阅读:2

(1)SpringBoot整合Spring(不存在)

(2)SpringBoot整合SpringMVC(不存在)

(3)SpringBoot整合MyBatis(主要)

一、新建springboot项目。

在application.yml配置文件中添加数据源信息

二、创建domain.book表对象

package com.itheima.domain;

public class Book {
private Integer id;
private String name;
private String type;
private String description;

@Override  
public String toString() {  
    return "Book{" +  
            "id=" + id +  
            ", name='" + name + '\\'' +  
            ", type='" + type + '\\'' +  
            ", description='" + description + '\\'' +  
            '}';  
}

public Integer getId() {  
    return id;  
}

public void setId(Integer id) {  
    this.id = id;  
}

public String getName() {  
    return name;  
}

public void setName(String name) {  
    this.name = name;  
}

public String getType() {  
    return type;  
}

public void setType(String type) {  
    this.type = type;  
}

public String getDescription() {  
    return description;  
}

public void setDescription(String description) {  
    this.description = description;  
}  

}

三、创建dao.BookDao接口,书写数据库方法

package com.itheima.dao;

import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface BookDao {
@Select("select * from tb_book where id = #{id}")
public Book getById(Integer id);
}

四、创建service.BookService接口,书写对应数据库方法

package com.itheima.service;

import com.itheima.domain.Book;

public interface BookService {
public Book getById(Integer id);
}

五、创建service.impl.BookServiceImpl类封装实现BookService接口方法。

package com.itheima.service.impl;

import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements BookService {

@Autowired  
private BookDao bookDao;

@Override  
public Book getById(Integer id) {  
    Book book = bookDao.getById(id);  
    return book;  
}  

}

六、在test中测试

package com.itheima;

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class Springboot08MybatisApplicationTests {

@Autowired  
private BookService bookService;

@Test  
void contextLoads() {  
    Book book = bookService.getById(12);  
    System.out.println(book);  
}

}

结果:

不用内置数据源,设置druid数据源。

在pom中添加druid依赖:


com.alibaba druid 1.1.16