Mybatis是一款优秀的持久层框架,相比于Hibernate等框架,Mybatis更加灵活,适用于各种规模和类型的项目。下面介绍一个Mybatis的使用案例:
假设有一张用户表user,其中包含id、name、age三个字段。我们需要通过Mybatis进行增删改查操作。
- 首先,需要在pom.xml文件中引入Mybatis的依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
-
创建User实体类,包含id、name、age三个属性,以及对应的getter和setter方法。
-
创建UserMapper接口,定义了对user表进行增删改查的方法,如下:
public interface UserMapper {
User selectById(int id);
List<User> selectAll();
void insert(User user);
void update(User user);
void deleteById(int id);
}
- 创建UserMapper.xml文件,并编写对应的SQL语句,如下:
<?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="selectById" resultType="com.example.entity.User">
select * from user where id = #{id}
</select>
<select id="selectAll" resultType="com.example.entity.User">
select * from user
</select>
<insert id="insert" parameterType="com.example.entity.User">
insert into user(name,age) values(#{name},#{age})
</insert>
<update id="update" parameterType="com.example.entity.User">
update user set name=#{name},age=#{age} where id=#{id}
</update>
<delete id="deleteById" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>
- 在Spring配置文件中配置SqlSessionFactoryBean,如下:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper" />
</bean>
- 在业务代码中使用UserMapper接口进行操作,如下:
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.selectById(id);
}
public List<User> getAllUsers() {
return userMapper.selectAll();
}
public void addUser(User user) {
userMapper.insert(user);
}
public void updateUser(User user) {
userMapper.update(user);
}
public void deleteUser(int id) {
userMapper.deleteById(id);
}
上述案例中,我们通过Mybatis框架来操作数据库,并完成了增删改查操作。通过配置SqlSessionFactoryBean和MapperScannerConfigurer,将Mapper接口注入到业务代码中,实现了数据库访问的解耦。

被折叠的 条评论
为什么被折叠?



