美文网首页
Spring Boot整合Mybatis

Spring Boot整合Mybatis

作者: Theon66 | 来源:发表于2018-02-03 20:15 被阅读0次

    1.添加依赖

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.3.1</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>   
    

    2.application.properties添加数据库连接信息

    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
    spring.datasource.username = root
    spring.datasource.password = root
    

    注意如果不写useSSL=false,控制台会打印警告信息

    3.编写mapper接口

    @Mapper
    public interface StudentMapper {
        @Select("SELECT * FROM Student WHERE sno = #{sno}")
        Student findBySno(@Param("sno") String sno);
    }
    

    4.编写application类

    @SpringBootApplication
    public class MybatisApplication implements CommandLineRunner {
    
        private final StudentMapper studentMapper;
        
        public MybatisApplication(StudentMapper studentMapper) {
            this.studentMapper = studentMapper;
        }   
        
        @Override
        public void run(String... arg0) throws Exception {
            System.out.println(studentMapper.findBySno("1").getSname());
        }
    
        public static void main(String[] args) {
            SpringApplication.run(MybatisApplication.class, args);
        }
    }
    

    运行此类便可看到结果

    相关文章

      网友评论

          本文标题:Spring Boot整合Mybatis

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