springboot+mybatis的實現以及 Property ‘sqlSessionFactory’ or ‘sqlSessionTemplate’ are required問題的解決
阿新 • • 發佈:2018-11-11
廢話不多說,直接上步驟
前期準備
建表:
CREATE TABLE book(id int primary key auto_increment ,bookId bigint,bookName varchar(200))
插入資料:
insert into book values(32165489,springboot_base);
1、先用idea建立一個springboot專案,建立步驟如下
**
這個步驟一定要注意了,我就是在這裡被坑了大發了,這裡如果勾選了mybatis,那麼按照正常的配置寫完後,執行會報錯:Property ‘sqlSessionFactory’ or ‘sqlSessionTemplate’ are required,切記不能勾選
**
2、pom.xml新增如下依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
3、編寫mapper,此處可以用@Mapper,也可以在 application處全域性配置,比如下面一個步驟
//@Mapper
@Repository
public interface BookMapper {
@Select("select * from book where bookId=#{bookId}")
Book findBookById(@Param("bookId") Long bookId);
}
4、application新增@MapperScan註解,路徑為mapper介面所在的包路徑
@SpringBootApplication
@MapperScan(basePackages = "com.mybatis1.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5、新建application.yml檔案,配置資料來源
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/springbootdb
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
6、編寫book的model類
public class Book {
private Integer id;
private Long bookId;
private String bookName;
set,get方法就不貼了
}
7、編寫test類
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
@Autowired
private BookMapper bookMapper;
@Test
public void getBookById(){
System.out.println(bookMapper.findBookById(654645L));
}
}
然後run這getBookById的方法,成功執行