02_mybatis的CRUD操作
1、XML 的实现
1.1 定义SQL映射xml文件
<insert id="insertUser" parameterType="cn.imentors.mybatis.test1.User">
insert into users(name, age) values(#{name}, #{age});
</insert>
<delete id="deleteUser" parameterType="int">
delete from users where id=#{id}
</delete>
<update id="updateUser" parameterType="cn.imentors.mybatis.test1.User">
update users set name=#{name},age=#{age} where id=#{id}
</update>
- parameterType="cn.imentors.mybatis.test1.User",这个参数类型是一个对象,所以占位符必须是对象的属性#{name}
1.2 在config.xml 中注册这个映射文件
<mappers>
<mapper resource="cn/imentors/mybatis/test1/UserMapper.xml"/>
</mappers>
</configuration>
1.3 MyBatisUtils
为了后面测试的方便,将conf.xml文件的加载,写成一个工具类
package cn.imentors.mybatis.util;
public class MybatisUtils {
public static SqlSessionFactory getFactory() {
String resource = "conf.xml";
InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
return factory;
}
}
1.4 测试CRUD操作的XML实现
- add
@Test
public void testAdd() {
SqlSessionFactory factory = MybatisUtils.getFactory();
//默认是手动提交的
SqlSession session = factory.openSession();
String statement = "cn.imentors.mybatis.test2.userMapper.insertUser";
int insert = session.insert(statement , new User(3, "KK", 23));
//提交
session.commit();
session.close();
System.out.println(insert);
}
- update
@Test
public void testUpate() {
SqlSessionFactory factory = MybatisUtils.getFactory();
//默认是手动提交的
SqlSession session = factory.openSession(true);
String statement = "cn.imentors.mybatis.test2.userMapper.updateUser";
int update = session.update(statement, new User(3, "KK444", 25));
session.close();
System.out.println(update);
}
- delete
@Test
public void testDelete() {
SqlSessionFactory factory = MybatisUtils.getFactory();
// 默认是手动提交的
SqlSession session = factory.openSession(true);
String statement = "cn.imentors.mybatis.test2.userMapper.deleteUser";
int delete = session.delete(statement, 3);
session.close();
System.out.println(delete);
}
2、注解的实现
2.1 定义SQL映射的接口
public interface UserMapper {
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int insertUser(User user);
@Delete("delete from users where id=#{id}")
public int deleteUserById(int id);
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int updateUser(User user);
@Select("select * from users where id=#{id}")
public User getUserById(int id);
@Select("select * from users")
public List<User> getAllUser();
}
2.2 在conf.xml中注册这个映射接口
<mapper class="cn.imentors.mybatis.test3.UserMapper"/>
2.3 测试
@Test
public void testAdd() {
SqlSessionFactory factory = MybatisUtils.getFactory();
//默认是手动提交的
SqlSession session = factory.openSession(true);
//加载UserMapper接口
UserMapper mapper = session.getMapper(UserMapper.class);
int add = mapper.add(new User(4, "SS", 45));
System.out.println(add);
session.close();
}
捐赠我们
良师益友工作室一直在致力于帮助编程爱好更加快速方便地学习编程,如果您对我们的成果表示认同并且觉得对你有所帮助,欢迎您对我们捐赠^_^。