通用mapper快速入门
导入依赖
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.3</version>
</dependency>
在applicationContext.xml添加此配置文件
<!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
<!-- 通用Mapper用tk,一般用org -->
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<!--扫描所有dao接口的实现,加入到ioc容器中 -->
<property name="basePackage" value="com.xiaoshu.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 通用Mapper -->
<property name="properties">
<value>
mappers=tk.mybatis.mapper.common.Mapper
</value>
</property>
</bean>
创建实体类user
/**
* 用户ID
*/
@Id
@Column(name = "userId")
private Integer userid;
/**
* 用户名
*/
@Column(name = "userName")
private String username;
/**
* 密码
*/
private String password;
/**
* 用户类型
*/
@Column(name = "userType")
private Byte usertype;
/**
* 角色ID
*/
@Column(name = "roleId")
private Integer roleid;
/**
* 描述信息
*/
@Column(name = "userDescription")
private String userdescription;
在dao层继承通用mapper接口
public interface UserMapper extends BaseMapper<User> {
}
常用方法
1)
select:
select(T record);
根据实体类中不为null的数据进行查询
selectByPrimaryKey(Object key);
根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
selectOne(T record);
根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,条件使用等号,不建议经常使用
2)
Insert:
insert(T record);
保存一个实体,null的属性也会保存,不会使用数据库默认值
insertSelective(T record);
保存一个实体,null的属性不会保存,会使用数据库默认值
3)
Update
updateByPrimaryKey(T record);
根据主键更新实体全部字段,null值会被更新
updateByPrimaryKeySelective(T record);
根据主键更新属性不为null的值
4)
Delete
delete(T record);
根据实体属性作为条件进行删除,查询条件使用等号
deleteByPrimaryKey(Object key);
根据主键字段进行删除,方法参数必须包含完整的主键属性
以上为通用mapper入门的使用方法