Spring Boot + MyBatis + MySql项目搭建

之前使用的是JPA+Hibernate。现在试水Mybatis,看看有什么不同。边做边学,首先把项目搭起来。

一、创建Spring Boot 项目

在IntelliJ IDEA新建一个Spring Boot项目:


image.png

image.png

image.png

image.png

然后在pom.xml可以看到已经有Mybatis和MySql Connector的依赖:


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


    mysql
    mysql-connector-java
    runtime

二、application.properties添加配置

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

大致上配置完成,接下来有两种开发方式:

1.注解

三、添加注解

在启动类添加MapperScan注解指定mapper包:

@MapperScan("com.null01.mapper")
@SpringBootApplication
public class MybatistestApplication {

   public static void main(String[] args) {
       SpringApplication.run(MybatistestApplication.class, args);
   }

}

四、编写实体类

public class Hotel {
    private Long id;
    private String hotelName;
    private String address;

    public Long getId() {
        return id;
    }

    public String getHotelName() {
        return hotelName;
    }

    public String getAddress() {
        return address;
    }

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

    public void setHotelName(String hotelName) {
        this.hotelName = hotelName;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

五、编写Mapper接口

public interface SalariesMapper {
    @Select("SELECT * FROM hotel")
    @Results({
            @Result(property = "id",  column = "id"),
            @Result(property = "hotelName", column = "hotel_name"),
            @Result(property = "address", column = "address"),
    })
    List getAll();
}

六、编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatistestApplicationTests {

    @Autowired
    private HotelMapper hotelMapper;

    @Test
    public void contextLoads() {
        List hotelList = hotelMapper.getAll();
        for(Hotel hotel:hotelList){
            System.out.println(hotel);
        }
    }

}

2.xml配置

三、application.properties增加两项配置

指定两种xml配置文件的存放地址


image.png
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml

四、mybatis-config.xml

总配置文件,用于配置数据源、事务管理器和mapper配置文件的地址,由于基本上都在application.properties里配了,现在暂时没什么用




五、/mapper/*.xml

mapper配置,sql和映射关系就是写在里面的




    
        
        
        
    

    

六、实体类和mapper接口

这两个还是需要,实体类和注解方式的一样,mapper去掉注解

@Mapper
public interface HotelMapper {
    List getAll();
}

七、测试类

可以沿用注解方式的测试类。至此,两种方式都搭通了。

你可能感兴趣的:(Spring Boot + MyBatis + MySql项目搭建)