Springboot+mybatis小demo

首先使用idea创建项目:
创建步骤:
一:点击Create New Project
二:选择Spring Initializr 然后点击 next


image.png

三:由于是测试我直接点击了下一步项目会默认创建项目名和包名:(此步骤可以自定义创建:项目名、包名;看个人需求)


image.png

四:在最左侧的选项中选择web 中Spring Web Starter 和 SQL选项中的 Mybatis Framework选择next
image.png

五:这时候点击finish就完成了项目的创建
image.png

创建好后就开始对项目进行配置:

1、pom文件配置:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.5.RELEASE
         
    
    com.example
    demo2
    0.0.1-SNAPSHOT
    demo2
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.1
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            mysql
            mysql-connector-java
        
        
        
            com.mchange
            c3p0
            0.9.5.2
        
        
            net.minidev
            json-smart
            2.3
            compile
        
        
        
            org.apache.poi
            poi
            3.10-FINAL
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



2、配置resources文件下的aplication.properties


server.port=8081
server.servlet.context-path=/demo

# mySql连接
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库库名?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=账号
jdbc.password=密码

# Mybatis配置
mybatis_config_file=mybatis-config
mapper_path=/mapper/**
entity_package=com.example.entity

3、在 com.example.demo2 包下创建一个config包,在config包内分别创建dao和service包:
在dao包内创建 DataSourceConfig.class 和 SessionFactoryConfiguration.class;
DataSourceConfig.class代码

package com.example.demo2.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyVetoException;

@Configuration
//配置mapper文件的扫描路径
@MapperScan("com.example.demo2.dao")
public class DataSourceConfig {
    @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="dataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        dataSource.setAutoCommitOnClose(false);
        return dataSource;
    }
}


SessionFactoryConfiguration.class代码

package com.example.demo2.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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;

@Configuration
public class SessionFactoryConfiguration {

    //mybatis-config.xml配置文件的路径
//    @Value("${mybatis_config_file}")
//    private String mybatisConfigFilePath;

    //mybatis mapper文件的路径
    @Value("${mapper_path}")
    private String mapperPath;

    //实体类所在的包
    @Value("${entity_package}")
    private String entityPackage;

    @Autowired
    @Qualifier("dataSource") //起个别名,要不然会报错
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //mapper文件的路径
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        //读取mapper文件
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSessionFactoryBean.setDataSource(dataSource);
        //映射实体类
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}

在service包内创建 TransactionManagementConfiguration.class 是对servce层事物的配置

package com.example.demo2.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);
    }
}

到此步骤对项目的配置算是完成了!
这时候在 com.example.demo2 包下分别创建entity 、dao 、service 、web 包:
dao包内创建bgm.class

package com.example.demo2.entity;

public class Bgm {
    private String id;
    private String author;
    private String name;
    private String path;

    public String getId() {
        return id;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getName() {
        return name;
    }

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

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public String toString() {
        return "Bgm{" +
                "id='" + id + '\'' +
                ", author='" + author + '\'' +
                ", name='" + name + '\'' +
                ", path='" + path + '\'' +
                '}';
    }
}

dao包内创建 BgmDao 接口

package com.example.demo2.dao;

import com.example.demo2.entity.Bgm;

import java.util.List;

public interface BgmDao {

    List queryBgm();

    Bgm queryBgmById(String id);

    int saveBgmManage (Bgm bgm);

    int updateBgm(Bgm bgm);

    int deleteBgmById(String id);

}

在resources文件下创建mapper文件夹,用于存放mapper.xml文件。
创建 BgmDaoMapper.xml






    

    

    
        insert into bgm(id,author,name,path) values (#{id},#{author},#{name},#{path})
    

    
        delete from bgm where id = #{id}
    

    
        update bgm set author = #{author} , name = #{name} , path = #{path} where id = #{id}
    

service包内创建 BgmService 接口

package com.example.demo2.service;

import com.example.demo2.entity.Bgm;

import java.util.List;

public interface BgmService {

    List getBgmList();

    Bgm getBgmById(String id);

    boolean saveBgmManage(Bgm bgm);

    boolean deleteBgmById(String id);

    boolean updateBgm(Bgm bgm);
}

在service包内创建一个 impl包用于实现接口

package com.example.demo2.service.impl;

import com.example.demo2.dao.BgmDao;
import com.example.demo2.entity.Bgm;
import com.example.demo2.service.BgmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static org.springframework.util.StringUtils.isEmpty;

@Service
public class BgmServiceImpl implements BgmService {

    @Autowired
    private BgmDao bgmDao;

    @Override
    public List getBgmList() {
        return bgmDao.queryBgm();
    }

    @Override
    public Bgm getBgmById(String id) {
        return bgmDao.queryBgmById(id);
    }

    @Transactional
    @Override
    public boolean saveBgmManage(Bgm bgm) {
        if (bgm.getName() != null && !"".equals(bgm.getName())) {
            try {
                int effectedNum = bgmDao.saveBgmManage(bgm);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new RuntimeException("插入失败!!!");
                }
            } catch (Exception e) {
                throw new RuntimeException("插入失败!!!" + e.getMessage());
            }
        } else {
            throw new RuntimeException("插入信息不能为空!!!");
        }
    }

    @Override
    public boolean deleteBgmById(String id) {
        if (id != null || id != ""){
            try{
                int effectedNum = bgmDao.deleteBgmById(id);
                if (effectedNum > 0){
                    return true;
                } else {
                    throw new RuntimeException("删除信息失败!!!");
                }
            }catch (Exception e){
                throw new RuntimeException("删除信息失败!!!" + e.toString());
            }
        } else {
            throw new RuntimeException("id不能为空!!!");
        }
    }

    @Override
    public boolean updateBgm(Bgm bgm) {
        if (!isEmpty(bgm)){
            try{
                int effectedNum = bgmDao.updateBgm(bgm);
                if (effectedNum > 0 ) {
                    return true;
                } else {
                    throw new RuntimeException("修改异常!!!");
                }
            }catch (Exception e){
                throw new RuntimeException("修改异常!!!");
            }

        } else {
            throw new RuntimeException("数据不能为空!!!");
        }
    }
}

web包内创建BgmController.class

package com.example.demo2.web;

import com.example.demo2.entity.Bgm;
import com.example.demo2.service.BgmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bgm")
public class BgmController {

    @Autowired
    private BgmService bgmService;

    @RequestMapping(value="/listBgm", method = RequestMethod.GET)
    public Map  listBgm(){
        Map modelList = new HashMap();
        List listBgm = bgmService.getBgmList();
        modelList.put("listBgm",listBgm);
        return  modelList ;
    }

    @RequestMapping(value = "/bgmById", method = RequestMethod.GET)
    public Map bgmById(String id){
        Map bgmMap = new HashMap();
        Bgm bgm = bgmService.getBgmById(id);
        bgmMap.put("bgm",bgm);
        return bgmMap;
    }

    @RequestMapping(value = "/saveBgmManage", method = RequestMethod.GET)
    public Map saveBgmManage(Bgm bgm){
        Map modelMap = new HashMap();
        modelMap.put("success",bgmService.saveBgmManage(bgm));
        return modelMap;
    }

    @RequestMapping(value = "/deleteBgmManage",method = RequestMethod.GET)
    public Map deleteBgmManage(String[] id){
        Map map = new HashMap<>();
        for (String i : id) {
            map.put("success",bgmService.deleteBgmById(i));
        }
        return map;
    }

    @RequestMapping(value = "/updateBgm",method = RequestMethod.GET)
    public Map updateBgm(Bgm bgm){
        Map map = new HashMap<>();
        map.put("success",bgmService.updateBgm(bgm));
        return map;
    }

}

项目整体结构


image.png

现在是已经把增删改查给写完了,在 Demo2Application.class类中点击右键启动 Run 就可以启动项目,在浏览器内访问web层接口就可以了

小弟技术有限,望大神纠错指正!!!

你可能感兴趣的:(Springboot+mybatis小demo)