之前分享过一篇spring boot集成mybatis的文章()
今天分享另一种spring boot 集成mybati的方法。
我使用的是idea做开发,用meven做管理,数据库用的是mysql。
1、使用idea创建spring boot 项目,数据库勾选mysql
2、配置数据库,个人喜欢用application.yml做配置,所以删除application.properties配 置,创建application.yml配置文件增加,数据库配置,如下:
spring:
datasource:
name: mysql
url: jdbc:mysql://127.0.0.1:3306/diary
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
3、引入Mapper通用依赖,在pom文件中加入下面这段代码:
4、创建mybatis配置类, 记得加@Configuration,这样标识这是一个配置类,在程序启动的时候 会被自动程序自动装载:
代码:
package com.lu.dev.diary.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;
import java.util.Properties;
@Configuration
public class MybatisConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.lu.dev.diary.access"); //dao文件所在包路径
Properties properties = new Properties();
properties.setProperty("notEmpty", "false");
properties.setProperty("IDENTITY", "MYSQL");
mapperScannerConfigurer.setProperties(properties);
return mapperScannerConfigurer;
}
}
5、创建controller,记得加@RestController注解
代码:
package com.lu.dev.diary.controller;
import com.lu.dev.diary.buniss.testService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
@RestController
@RequestMapping("/demo/srv")
public class testController {
@Autowired
testService service;
@RequestMapping(value="/test", method = RequestMethod.GET)
public List
try {
List
return list;
}
catch (Exception ex)
{
throw ex;
}
}
}
6、创建service,记得加注解@Service:
代码:
package com.lu.dev.diary.buniss;
import java.util.HashMap;
import java.util.List;
public interface testService {
List
}
代码:
package com.lu.dev.diary.buniss;
import com.lu.dev.diary.access.testDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
@Service("testService")
public class testServiceImpl implements testService {
@Autowired
testDao dao;
@Override
public List
return dao.getDiaryList();
}
}
7、创建Dao,记得加@Mapper注解:
代码:
package com.lu.dev.diary.access;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.HashMap;
import java.util.List;
@Mapper
public interface testDao {
@Select("SELECT t.user_id,t.title FROM t_diary t")
List
}
这里的Dao里的方法的实现是直接同过注解的方式写sql,而不是把sql写在xml文件里。
这样的写法个人觉得开发起来方便了,但是写一些复杂的sql就没有像写在xml里那么灵活了。
不知大家有没有什么其他看法,欢迎提出来,大家一起探讨,一起进步!
閱讀更多 匠心一笑 的文章