mybatis的mapper层怎么写
时间: 2024-05-14 12:07:31 浏览: 80
MyBatis的Mapper层是用于定义数据访问方法的接口,具体实现由MyBatis框架自动生成。下面是一个简单的示例:
定义数据访问方法的接口:
```java
public interface UserMapper {
User getUserById(int id);
List<User> getUsers();
void addUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
```
其中,User是一个实体类,包含用户信息。
MyBatis会根据接口方法的名称和参数类型自动生成SQL语句,实现数据的CRUD操作。例如,getUserById方法对应的SQL语句可以是:
```xml
<select id="getUserById" resultType="User">
select * from user where id = #{id}
</select>
```
在MyBatis的配置文件中,需要将Mapper接口和对应的SQL语句进行映射:
```xml
<mappers>
<mapper class="com.example.UserMapper">
<select id="getUserById" resultType="User">
select * from user where id = #{id}
</select>
<select id="getUsers" resultType="User">
select * from user
</select>
<insert id="addUser">
insert into user(id, name, age) values(#{id}, #{name}, #{age})
</insert>
<update id="updateUser">
update user set name=#{name}, age=#{age} where id=#{id}
</update>
<delete id="deleteUser">
delete from user where id=#{id}
</delete>
</mapper>
</mappers>
```
这样,在使用Mapper接口的时候,MyBatis就会自动调用对应的SQL语句进行数据访问。例如:
```java
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
List<User> users = userMapper.getUsers();
userMapper.addUser(new User(2, "Tom", 20));
userMapper.updateUser(new User(2, "Tom", 21));
userMapper.deleteUser(2);
sqlSession.commit();
sqlSession.close();
```
这样就完成了Mapper层的编写。
阅读全文