整合Mybatis
一、Mybatis导入
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
二、使用步骤
1.在接口上使用注解
import com.example.mapper.UserMapper;
import com.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/query")
@ResponseBody
public List<User> queryUsers(){
List<User> users = userMapper.queryUsers();
users.stream().forEach(x->{
System.out.println(x);
});
return users;
}
}
import com.example.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//表示本类是一个mybatis的接口
@Mapper
@Repository
public interface UserMapper {
List<User> queryUsers();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
<?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.yuzhenwu.mapper.UserMapper">
<select id="queryUsers" resultType="User">
select * from user;
</select>
<select id="queryUserById" resultType="User">
select * from user where id = #{id};
</select>
<insert id="addUser" parameterType="User">
insert into mybatis.user(id, name, pwd) VALUES (#{id},#{name},#{pwd});
</insert>
<update id="updateUser" parameterType="User">
update user set name = #{name},pwd=#{pwd} where id = #{id};
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id};
</delete>
</mapper>
``