我们在这里写一下集成mybatis的几个步骤以及一个小实例
一、集成mybatis
和集成mysql看上去差不多,还是第一步,pom.xml中向<dependencies> </dependencies>
加入下面的内容
<!--引入mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
导入pom依赖之后,打开application.yml中写入下面内容
#集成mybatis
mybatis:
#配置Mapper.xml的文件位置
mapper-locations: classpath:mapper/*Mapper.xml
#mybatis中对应的实体类存放的位置
type-aliases-package: com.pro.sweet.entity
诺,简简单单的就完成了mybatis的配置。完成了mybatis的配置,当然就要试一下好不好用了,现在简单写个实例吧
首先简单创建目录结构如下:(均为目录结构,无文件,截图不便,凑合看一下)
java
com.pro.sweet
controller
service
impl
entity
mapper
resources
mapper
config
static
1、在resources/mapper/config下创建文件sqlMapConfig.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
此文件内可以封装一些常用的Map啥的,这里我就不赘述了
2、在resources/mapper下创建文件UserMapper.xml,内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.pro.work.sweet.mapper.UserMapper">
<select id="login" resultType="User">
select * from user_table where userid = #{userId} and pwd = #{pwd}
</select>
</mapper>
namespace可指定你的*Mapper.java所在的位置,mapper标签内写sql
3、在com.pro.sweet.entity中创建接收数据库返回的实体类User,这个应该不用写了吧
4、在com.pro.sweet.mapper创建UserMapper.java,代码如下:
package com.pro.work.sweet.mapper;
import com.pro.work.sweet.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
User login(User user);
}
5、然后我们写service以及实现层Impl
在com.pro.sweet.service下创建UserService.java,代码如下:
package com.pro.work.sweet.service;
import com.pro.work.sweet.entity.RegisterUserParam;
import com.pro.work.sweet.entity.User;
import java.util.List;
public interface UserService {
/**
* 登录
* @param user
* @return
*/
User login(User user);
}
在com.pro.sweet.service.impl下创建UserServiceImpl.java,代码如下:
package com.pro.work.sweet.service.impl;
import com.pro.work.sweet.entity.User;
import com.pro.work.sweet.mapper.UserMapper;
import com.pro.work.sweet.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper ;
@Override
public User login(User user) {
return userMapper.login(user);
}
}
6、接下来就是封装contoller了,这个我就不写了,应该都会。
至此:mysql及mybatis集成完毕,测试一下好不好用吧
注:关于SpringBoot对于事物的集成,很简单。在启动类中加入@EnableMicroserviceApplication,在impl下的实现类中,需要启用事务的方法上加一个@Transactional即可