美文网首页
新建一个SpringBoot加MyBatis工程,连接数据库进行

新建一个SpringBoot加MyBatis工程,连接数据库进行

作者: 真的傅鹏程 | 来源:发表于2019-04-08 21:02 被阅读0次

    spring官网

    选择Maven Project

    选择Java

    选择2.1.4

    选择依赖Web,MySql,MyBatis

    重命名后缀名application.yml

    以下在application.yml配置数据库信息和端口信息
    server:
      port: 9999
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/books?useSSLL=true&serverTimezone=UTC
        username: root
        password: root
    
    mybatis:
      configuration:
        map-underscore-to-camel-case: true
    
    

    在*****Application同级目录下新建service,mapper,domain,controller四个文件夹

    后期会记录第三方类一键生成。以及存贮过程

    在domain目录下新建BookInfo.class

    public class BookInfo {
    
        private Integer bookId;
    
        private String bookName;
        private String bookAuthor;
        private BigDecimal bookPrice;
        private Date bookDate;
    
        ...省略set,get
    }
    
    

    在mapper目录下新建BookMapper.class

    @Mapper
    @Repository("bookMapper")
    public interface BookMapper {
    
    
        @Select("select b_id,b_auther,b_name,b_price,b_date from t_books where book_id=#{bookId}")
        BookInfo getBookById(@Param("bookId") Integer bookId);
    
    }
    
    

    在service目录下新建BookService.class和BookServiceImpl.class

    public interface BookService {
    
        BookInfo getBookById(Integer bookId);
    }
    
    

    BookServiceImpl.class

    @Service("bookService")
    public class BookServiceImpl implements BookService{
    
        @Autowired
        private BookMapper mapper;
    
        @Override
        public BookInfo getBookById(Integer bookId) {
            return mapper.getBookById(bookId);
        }
    }
    
    

    在controller目录下新建BookController.class

    @RestController
    @RequestMapping("book")
    public class BookController {
    
        @Autowired
        private BookService bookService;
    
        @GetMapping("id/{bookId}")
        public BookInfo getBook(@PathVariable("bookId") Integer bookId){
            return bookService.getBookById(bookId);
        }
    }
    
    

    这里返回json,如要返回xml,加入依赖jackson-dataformat-xml 即可

            <dependency>
                <groupId>com.fasterxml.jackson.dataformat</groupId>
                <artifactId>jackson-dataformat-xml</artifactId>
            </dependency>
            
            
            然后getmapping(...省略 , produces = MediaType.APPLICATION_XML_VALUE)
    

    这些比较简单,再次记录一下。

    相关文章

      网友评论

          本文标题:新建一个SpringBoot加MyBatis工程,连接数据库进行

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