mybatismapper怎么写
时间: 2023-08-02 22:10:52 浏览: 157
mybatis-mapper
MyBatis是一种支持定制化SQL、存储过程和高级映射的优秀的持久层框架,它的Mapper接口是MyBatis的一个重要组成部分,用于将Java方法与SQL语句进行映射。下面是一个简单的MyBatis Mapper的写法示例:
1. 定义实体类
```java
public class User {
private Integer id;
private String username;
private String password;
// 省略getter/setter方法
}
```
2. 编写Mapper映射文件
在resources目录下创建mapper目录,并在mapper目录下创建UserMapper.xml文件,该文件用于定义SQL语句和映射关系。
```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.example.mapper.UserMapper">
<!-- 定义查询语句 -->
<select id="getUserById" parameterType="int" resultType="User">
select * from user where id = #{id}
</select>
<!-- 定义插入语句 -->
<insert id="addUser" parameterType="User">
insert into user(username, password) values(#{username}, #{password})
</insert>
<!-- 定义更新语句 -->
<update id="updateUser" parameterType="User">
update user set username = #{username}, password = #{password} where id = #{id}
</update>
<!-- 定义删除语句 -->
<delete id="deleteUserById" parameterType="int">
delete from user where id = #{id}
</delete>
</mapper>
```
3. 编写Mapper接口
在Java包com.example.mapper下创建UserMapper接口,该接口用于定义方法与SQL的映射关系。
```java
public interface UserMapper {
User getUserById(int id);
void addUser(User user);
void updateUser(User user);
void deleteUserById(int id);
}
```
4. 配置MyBatis
在resources目录下创建mybatis-config.xml文件,该文件用于配置MyBatis的全局属性和插件。
```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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
```
5. 使用Mapper
```java
public class Main {
public static void main(String[] args) {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
}
```
以上是一个简单的MyBatis Mapper的写法示例,具体的实现方式可以根据具体的业务需求进行调整和优化。
阅读全文