您的位置:首页 > 移动开发

Mybatis Mapper的class写法

2016-05-02 18:45 375 查看

使用Mybatis的时候需要写mapper.xml来映射实体类和数据表字段

mapper.xml也是官方推荐的用法,现在我们用带注解的class来实现mapper.xml

 

代码如下:

顺便配置了一下CRUD的缓存,如果不用缓存,把@CacheNamespace和@Options去掉就行,他们配置的是缓存类型和缓存时间

public class User {

private String userName;
private String password;
private Boolean enable;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public Boolean getEnable() {
return enable;
}

public void setEnable(Boolean enable) {
this.enable = enable;
}

}

 

 

import java.util.List;

import org.apache.ibatis.annotations.CacheNamespace;
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.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@CacheNamespace
public interface UserMapper {

@Options(flushCache = true, timeout = 20000)
@Insert("insert into demo.user(user_name, password, enable) values(#{userName}, #{password}, #{enable})")
public void insert(User object);

@Options(flushCache = true, timeout = 20000)
@Update("update demo.user set password=#{password}, enable=#{enable} where user_name=#{userName}")
public void update(User object);

@Options(useCache = true, flushCache = false, timeout = 10000)
@Select("select * from demo.user where user_name=#{userName}")
@Results(value = {
@Result(id = true, property = "userName", column = "user_name"),
@Result(property = "password", column = "password"),
@Result(property = "enable", column = "enable"),
})
public List<User> query(@Param("userName") String userName);

@Options(flushCache = true, timeout = 20000)
@Delete("delete from demo.user where user_name=#{userName}")
public void delete(@Param("userName") String userName);

}

 

使用:

@Autowired
private SqlSessionFactory sqlSessionFactory;

@Test
public void testInsert() {
User user = new User("username", "password", true);
sqlSessionFactory.openSession().getMapper(UserMapper.class).insert(user);
}

 

注意,如果需要映射一对多的关系,还是老老实实用xml,毕竟mybatis的注解还不完善,简单的实体用class风格还是不错的,挺方便,而且如果需要mapper.xml和class风格的mapper混用,也是可以滴(在class中使用@ResultMap和mapper.xml进行合体)

 

以上

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: