欢迎投稿

今日深度:

Mybatis之使用注解开发CRUD,mybatis注解crud

Mybatis之使用注解开发CRUD,mybatis注解crud


上一篇演示了如何使用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();
	}



mybatis怎实现对象参数与注解参数同时传入

自定义对象也用@param注解.
在mapper.xml中使用的时候,#{对象别名.属性名},如#{user.id}
注意,使用了@pram注解的话在mapper.xml不加parameterType。
public List<UserExtension> selectAllUsers( @Param("user") UserExtension user, @Param("begin") int begin, @Param("end") int end);
 

只使用mybatis不用spring怎管理事务?最好有代码带注释的

全过程,自己管理
 

www.htsjk.Com true http://www.htsjk.com/shujukunews/3739.html NewsArticle Mybatis之使用注解开发CRUD,mybatis注解crud 上一篇演示了如何使用XML来操作Mybatis实现CRUD,但是大量的XML配置文件的编写是非常烦人的。因此 Mybatis也提供了基于注解的配置方式,下面我们...
相关文章
    暂无相关文章
评论暂时关闭