> 데이터 베이스 > MySQL 튜토리얼 > Mybatis之使用注解开发CRUD

Mybatis之使用注解开发CRUD

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2016-06-07 16:04:40
원래의
1111명이 탐색했습니다.

上一篇演示了如何使用XML来操作Mybatis实现CRUD,但是大量的XML配置文件的编写是非常烦人的。因此 Mybatis也提供了基于注解的配置方式,下面我们来演示一下使用接口加注解来实现CRUD的的例子。 首先是创建一个接口。 package com.bird.mybatis.bean;import j

上一篇演示了如何使用XML来操作Mybatis实现CRUD,但是大量的XML配置文件的编写是非常烦人的。因此

Mybatis也提供了基于注解的配置方式,下面我们来演示一下使用接口加注解来实现CRUD的的例子。

首先是创建一个接口。

package com.bird.mybatis.bean;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

public interface UserMapper {
	@Insert("insert into users(name, age) values(#{name}, #{age})")
	public int add(Users user);
	
	@Delete("delete from users where id = #{id}")
	public int deleteById(int id);
	
	@Update("update users set name = #{name}, age = #{age} where id = #{id}")
	public int update(Users user);
	
	@Select("select * from users where id = #{id}")
	public Users getUserById(int id);
	
	@Select("select * from users")
	public List<Users> getAllUsers();
}
로그인 후 복사
然后一定不要忘了在conf.xml配置文件中,注册这个类
<mappers>
		<mapper resource="com/bird/mybatis/bean/userMapper.xml" />
		<mapper class="com.bird.mybatis.bean.UserMapper"/>
	</mappers>
로그인 후 복사
下面就是使用这个类了
@Test
	public void testAdd2() {
		SqlSession openSession = factory.openSession();
		UserMapper mapper = openSession.getMapper(UserMapper.class);
		mapper.add(new Users(-1,"娃娃",99));
		openSession.commit();
		openSession.close();
	}
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿