SpringBoot整合MyBatis例子

1、pom.xml

 



	4.0.0

	com.java
	HelloWorldSpringBoot
	0.0.1-SNAPSHOT
	war

	HelloWorldSpringBoot
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.7.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-tomcat
			provided
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework.boot
			spring-boot-configuration-processor
			true
		
		 
                javax.servlet
                javax.servlet-api
                provided
         
         
                javax.servlet
                jstl
         

         
         	org.springframework.boot
         	spring-boot-starter-thymeleaf
         
         
         	org.springframework.boot
         	spring-boot-starter-freemarker
         


         
         	mysql
         	mysql-connector-java
         	runtime
         
         
         	org.springframework.boot
         	spring-boot-starter-data-jpa
         

         
         	org.mybatis.spring.boot
         	mybatis-spring-boot-starter
         	1.3.1
         
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


 

 

 

2、项目结构

 

SpringBoot整合MyBatis例子_第1张图片

 

3、application.yml

 

server:
  port: 8080
  context-path: /
  
helloWorld: Hi,SpringBoot!  

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db_book
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
      show-sql: true
      
mybatis: 
  mapperLocations: classpath:mapper/*.xml
  typeAliasesPackage: com.java.entity 


注意:是yml文件,不是xml文件!

 

 

4、mybatis基础配置

 

/**
 * MyBatis基础配置
 *
 * @author liuzh
 * @since 2015-12-19 10:11
 */
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {

    @Autowired
    DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.java.entity");

        //分页插件
       // ParserHelper pageHelper = new ParserHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
     
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}

 


5、mybaits接口扫描

 

 

/**
 * MyBatis扫描接口
 * 
 * @author liuzh
 * @since 2015-12-19 14:46
 */
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.java.mapper");
        return mapperScannerConfigurer;
    }

}

 

 

 

 

 

6、SpringBoot Application启动

 

@SpringBootApplication
@MapperScan(basePackages = "com.java.dao")
public class HelloWorldSpringBootApplication {

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

 

 

7、Controller层

 

@RestController
@RequestMapping("/book")
public class BookController {

	@Value("${helloWorld}")
	private String hello;
	
	@Resource
	private BookDao bookDao;
	
	@RequestMapping("/helloWorld")
	public String say() {
		System.out.println(hello);
		return "Hello SpringBoot";
	}

	
	/**
	 * 查找所有
	 * @return
	 */
	@RequestMapping("/findAllList")
	public ModelAndView findAllList() {
		ModelAndView  mav = new ModelAndView("bookList");
		List bookList = bookDao.findAll();
		mav.addObject("bookList", bookList);
		return mav;
	}
	
}

 

 

 

 

 

8、Dao层

 

public interface BookDao {
	
	public List findAll();

}

 

 

 

9、mapper

 

 


	
	
	
 

 


10、Thymeleaf模板引擎

 

 





图书管理



	<#list bookList as book>
	
操作 编号 图书名称 图书作者
${book.id} ${book.name} ${book.author}

 

 

 

11、数据库表结构

 

 

CREATE TABLE `t_book` (
  `id` varchar(255) NOT NULL,
  `name` varchar(100) DEFAULT NULL,
  `author` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

 

 

 

 

 

启动HelloWorldSpringBootApplication,请求http://localhost:8080/book/findAllList即可

 

12、效果

SpringBoot整合MyBatis例子_第2张图片

 

2018.11.13更新

本文成文与2017.11.06,一年之后,SpringBoot推出了2.0,MySQL数据库推出了8.0。如果使用SpringBoot2.0 + MyBatis + MySQL8.0,可参考https://blog.csdn.net/ryelqy/article/details/84030884解决兼容问题。

 

Reference:

[1] isea533, Spring Boot 集成MyBatis, http://blog.csdn.net/isea533/article/details/50359390
[2] 编程点滴, Spring Boot 整合 MyBatis, http://www.cnblogs.com/powercto/p/6717874.html

 

 

 

 

你可能感兴趣的:(SpringBoot,MyBatis)