SpringBoot与SpringFrameWork最大的区别是约定优于配置,今天尝试下如何使用注解而不是基于XML配置来使用Mybatis
【SpringBoot集成Mybatis】
1.pom依赖配置
<!-- 导入Mysql数据库链接jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
2.dataSource设置,springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3308/xxx?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = xxx
spring.datasource.password = xxx
3.定义业务模型和Mybatis的dao接口(mapper),Mapper注解是关键
package com.app.base;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper
{
//CREATE TABLE IF NOT EXISTS `user_tbl`(`id` INT UNSIGNED ,`properity` VARCHAR(400)
//NOT NULL,`val` VARCHAR(400) NOT NULL,PRIMARY KEY(`id`) ) ENGINE=InnoDB DEFAULT
//CHARSET=utf8;
@Select("select * from user_tbl")
public List<User> select(User parm);
}
package com.app.base;
import lombok.Getter;
import lombok.Setter;
public class User
{
@Getter
@Setter
private int id;
@Getter
@Setter
private String properity;
@Getter
@Setter
private String val;
}
4.SpringBoot启动项中设置扫描自定义mapper和加载datasource的 properties配置
@MapperScan("com.app.base")
@Configuration
@ComponentScan(basePackages={"com.app"})
@MapperScan("com.app.base")
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix="jdbc")
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
5.数据库操作层Dao,
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
@Service
public class Dao
{
@Autowired
private UserMapper mapPer;
@PostConstruct
private void init()
{
List<User> results = mapPer.select(null);
System.out.print(results.get(0).getProperity());
}
}