欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot+Mybatis新手入门

程序员文章站 2022-05-26 11:30:02
...

SpringBoot对比于SpringMVC减少了很多配置文件,在搭建时更加快捷方便,由于内置了tomcat所以直接运行Application不需要在tomcat中运行。

1 在eclipse中新建maven项目,并按以下配置书写pom.xml

<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>
  <groupId>SpringBoot</groupId>
  <artifactId>SpringBoot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

            <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
             <!--对Jsp支持 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <!-- 支持jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

            <!-- 支持oracle -->
        <dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc14</artifactId>
    <version>10.2.0.2.0</version>
</dependency>


    </dependencies>





  <build>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-compiler-plugin</artifactId>
             <version>3.1</version>
             <configuration>
                 <source>1.7</source>    <!-- Java版本号 --> 
                 <target>1.7</target>    
             </configuration>
</plugin>
</plugins>
</build>


</project>

2 新建如下目录结构
SpringBoot+Mybatis新手入门

3 加载完jar包后,新建启动类application,启动类必须放在最外层,加载的时候会加载application所在目录及下级目录

package com.springboot.SpringBootHello;

import org.apache.log4j.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
//此注解表示动态扫描DAO接口所在包
@MapperScan("com.springboot.SpringBootHello.dao")

//此注解表示该类启动类
@SpringBootApplication
public class Application implements  EmbeddedServletContainerCustomizer{
    private static Logger logger = Logger.getLogger(Application.class);

    public static void main(String[] args) {
        logger.info("=================开始成功=================");
        SpringApplication.run(Application.class, args);
        logger.info("=================启动成功=================");
    }
//这里是代码设置端口,也可以在application.properties文件中配置端口
    @Override
    public void customize(ConfigurableEmbeddedServletContainer cus) {
        // TODO Auto-generated method stub
        cus.setPort(8989);

    }
}

4 新建controller类,拦截动作

package com.springboot.SpringBootHello.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.springboot.SpringBootHello.model.User;
import com.springboot.SpringBootHello.service.UserService;


//只需使用@Controller 标记一个类是Controller ,然后使用@RequestMapping 和@RequestParam 等一些注解用以定义URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到。
@Controller
public class IndexController {

    private static Logger logger = Logger.getLogger(IndexController.class);

    @RequestMapping("/hello")
     @ResponseBody
    public String index() {

        logger.info("=====进入index=====");

        return "hello";

    }
}   

在浏览器中输入地址:
SpringBoot+Mybatis新手入门

===========上述操作后SpringBoot搭建的web的demon就好了=============

===============下面将Mybatis整合入SpringBoot中====================

1 首先确认在pom.xml中加载了mybatis及oracle驱动的包。
2 书写相关配置文件resource/config/application.propertities

#设置Tomcat端口,默认8080,此处端口也可在代码中设置,前文有提示
#server.port=8080
#设置项目ContextPath
server.context-path=/
#设置Tomcat编码
server.tomcat.uri-encoding=UTF-8
#设置视图解析器路径
spring.mvc.view.prefix=/WEB-INF/views/
#设置视图解析器后缀
spring.mvc.view.suffix=.jsp

#数据库配置
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
spring.datasource.username=eastcom
spring.datasource.password=eastcom
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

#配置.xml文件
mybatis.mapper-locations=classpath:mappings/*.xml
#配置模型路径
mybatis.type-aliases-package=com.springboot.SpringBootHello.model

3书写maybatis的mapper文件/resources/mappings/UserMapper.xml (需在application.propertities中书写加载的路径
)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<!--对应项目中的dao路径-->
<mapper namespace="com.springboot.SpringBootHello.dao.UserDao">


    <select id="getNameById" parameterType="com.springboot.SpringBootHello.model.User" resultType="com.springboot.SpringBootHello.model.User">
        SELECT * FROM user1 WHERE ID = #{id}
    </select>
</mapper>

4新建UserDao类

package com.springboot.SpringBootHello.dao;

import org.apache.ibatis.annotations.Mapper;

import com.springboot.SpringBootHello.model.User;

//mybatis
@Mapper
public interface UserDao {
        public User getNameById(User user);
}

5新建User模型类

package com.springboot.SpringBootHello.model;

public class User {
private  String name;
private Integer id;
private Integer age;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Integer getId() {
    return id;
}
public void setId(Integer id) {
    this.id = id;
}
public Integer getAge() {
    return age;
}
public void setAge(Integer age) {
    this.age = age;
}
}

6新建服务类

package com.springboot.SpringBootHello.service;

import com.springboot.SpringBootHello.model.User;

public interface UserService {

    public User getNameById(User user);
}

7新建实现类

package com.springboot.SpringBootHello.serviceImply;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springboot.SpringBootHello.dao.UserDao;
import com.springboot.SpringBootHello.model.User;
import com.springboot.SpringBootHello.service.UserService;
@Service
public class UserServiceImply implements UserService{
    @Autowired
    private UserDao userdao;
    @Override
    public User getNameById(User user) {
        // TODO Auto-generated method stub
        return userdao.getNameById(user);
    }

}

8修改controller

package com.springboot.SpringBootHello.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.springboot.SpringBootHello.model.User;
import com.springboot.SpringBootHello.service.UserService;



@Controller
public class IndexController {

    @Autowired
    private UserService userService;

    private static Logger logger = Logger.getLogger(IndexController.class);

    @RequestMapping("/hello")
     @ResponseBody
    public String index() {

        logger.info("=====进入index=====");

        return "hello";

    }



    @RequestMapping("/get")
     @ResponseBody
    public String get(User user) {

        logger.info("=====进入get=====");
        User user2=userService.getNameById(user);
        return user2.getName()+user2.getId()+user2.getAge();

    }
}

结果如图SpringBoot+Mybatis新手入门

注意事项:
配置文件:
pom.xml (Springboot,web,mybatis,tomcat,oracle等相关依赖)
application.properties和xml的路径需要在resources下
application.java需要放在最外层

理解以**解的含义及用法
@MapperScan
@Mapper
@SpringBootApplication
@Autowired
@Service
@RequestMapping(“/”)

相关标签: SpringBoot Mybatis