Spring Boot 集成Mybatis操作数据库

项目结构
    
pom配置

org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1




mysql
mysql-connector-java
5.1.39
application.properties 
#MySQL
spring.datasource.url=jdbc:mysql://localhost:3307/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
#mybatis.mapper-locations = classpath*:com/demo/mapper/*.xml
mybatis.mapper-locations = com/demo/mapper/*.xml

logging.level.sample.mybatis.mapper=TRACE
CityService.java
/**
* City业务类
*
* @author [email protected]
* @date 2017/1/9 14:59
*/
@Service()
// @Transactional
public class CityService extends BaseService {

@Autowired
private CityMapper cityMapper;

@Autowired
private CityDao cityDao;

/**
* 通过注解的形式查询数据库
*
* @return
*/
public City selectOneCityByStateUseAnnotation() {
return cityMapper.selectOneCityByState("CA1");
}

/**
* 使用@Mapper映射XML 查询数据
*
* @return
*/
public City selectOneCityByIdUseMapper(long id) {
return cityMapper.selectOneCityById(id);
}

/**
* 使用XML的形式查询数据库
*
* @return
*/
public City selectOneCityByIdUseXML(long id) {
return cityDao.selectOneCityById(id);
}
}
CityDao.java 传统的sqlSession方式
/**
* CityDao 使用sqlSession的形式查询数据
*
* @author [email protected]
* @date 2017/1/9 14:52
*/
@Component
public class CityDao {
@Autowired
private SqlSession sqlSession;

public City selectOneCityById(long id) {
return this.sqlSession.selectOne("selectOneCityById", id);
}

}
CityMapper.java 注解的方式
/**
* CityMapper 直接使用注解的形式查询数据库
*
* @author [email protected]
* @date 2017/1/9 14:57
*/
@Mapper
public interface CityMapper {

/**
* sql直接使用注解 不使用xml形式
*
* @param state
* @return
*/
@Select("select * from city where state = #{state}")
City selectOneCityByState(@Param("state") String state);

/**
* 使用xml形式,xml id默认为方法名
*
* @param id
* @return
*/
City selectOneCityById(long id);

}
CityMapper.xml
xml version="1.0" encoding="UTF-8" ?>
"-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
namespace="com.demo.mapper.CityMapper">



CityServiceTest.java
@RunWith(SpringRunner.class)
@SpringBootTest
public class CityServiceTest {

@Autowired
private CityService cityService;

/**
* 使用注解查询数据库
*/
@Test
public void selectOneCityByStateUseAnnotationTest() {
City city = cityService.selectOneCityByStateUseAnnotation();
System.out.println(city.toString());
}

/**
* 使用@Mapper映射XML 查询数据
*/
@Test
public void selectOneCityByIdUseMapperTest() {
City city = cityService.selectOneCityByIdUseMapper(2);
System.out.println(city.toString());
}

/**
* 使用XML的形式查询数据库
*/
@Test
public void selectOneCityByIdUseXMLTest() {
City city = cityService.selectOneCityByIdUseXML(2);
System.out.println(city.toString());
}

}


参考
         mybatis-spring-boot-autoconfigure

代码
         https://github.com/JeromeSuz/demo_spring_boot

你可能感兴趣的:(Spring,Spring,Boot)