MyBatis 基于注解的增、删、改、查操作
程序清单:UserMapper.java
package com.mapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.po.User;
public interface UserMapper {
@Insert("insert into t_user (name,sex,age) values(#{name},#{sex},#{age})")
@Options(useGeneratedKeys=true,keyProperty="id")
int addUser(User user);
@Select("select * from t_user where id=#{id}")
User getUserById(Integer id);
@Delete("delete from t_user where id=#{id}")
int deleteUser(@Param("id") Integer id);
@Update("update t_user set name=#{name},sex=#{sex},age=#{age} where id=#{id}")
void updateUser(User user);
}
配置mybatis-config.xml
<!-- 配置Mapper的位置 -->
<mappers>
<mapper class="com.mapper.UserMapper" />
</mappers>
测试@Insert注解
@Test
public void test() throws IOException {
session=MySqlSessionFactory.getSqlSession();
UserMapper um=session.getMapper(UserMapper.class);
User user=new User();
user.setName("tom");
user.setSex("男");
user.setAge(25);
um.addUser(user);
session.commit();
System.out.println("添加用户成功,id为:"+user.getId());
}
控制台输出如下:
测试@Delete注解
@Test
public void test() throws IOException {
session=MySqlSessionFactory.getSqlSession();
UserMapper um=session.getMapper(UserMapper.class);
um.deleteUser(2);
session.commit();
}
控制台输出如下:
测试@Update注解
@Test
public void test() throws IOException {
session=MySqlSessionFactory.getSqlSession();
UserMapper um=session.getMapper(UserMapper.class);
User user=um.getUserById(1);
user.setName("白雪");
user.setAge(18);
um.updateUser(user);
session.commit();
}
控制台输出如下:
测试@Select注解
@Test
public void test() throws IOException {
session=MySqlSessionFactory.getSqlSession();
UserMapper um=session.getMapper(UserMapper.class);
User user=um.getUserById(1);
System.out.println(user);
}
控制台输出如下: