SpringBoot使用
通用mapper
1.引入依赖
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
2.写bean类
//表名和类名一致可以省略
@Table(name = "tb_user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 用户名
//自动转换下换线到驼峰命名user_name -> userName
private String userName;
// 密码
private String password;
// 姓名
private String name;
// 年龄
private Integer age;
// 性别,1男性,2女性
private Integer sex;
// 出生日期
private Date birthday;
// 创建时间
private Date created;
// 更新时间
private Date updated;
// 备注
private String note;
}
3.dao层
- 注意导包要导tk.mybatis.mapper.common.Mapper
import com.hsp.bean.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserMapper extends Mapper<User> {
}
4.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper mapper;
@Test
public void findall(){
for (User user : mapper.selectAll()) {
System.out.println(user);
}
}
}
一旦继承了Mapper,继承的Mapper就拥有了Mapper所有的通用方法:
Select 方法: List<T> select(T record); 说明:根据实体中的属性值进行查询,查询条件使用等号
方法: T selectByPrimaryKey(Object key); 说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,
查询条件使用等号
方法: List<T> selectAll(); 说明:查询全部结果,select(null)方法能达到同样的效果
方法: T selectOne(T record); 说明:根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异
常,查询条件使用等号
方法: int selectCount(T record); 说明:根据实体中的属性查询总数,查询条件使用等号
Insert 方法: int insert(T record); 说明:保存一个实体,null的属性也会保存,不会使用数据库默认值
方法: int insertSelective(T record); 说明:保存一个实体,null的属性不会保存,会使用数据库默认值
Update 方法: int updateByPrimaryKey(T record); 说明:根据主键更新实体全部字段,null值会被更新
方法: int updateByPrimaryKeySelective(T record); 说明:根据主键更新属性不为null的值
Delete 方法: int delete(T record); 说明:根据实体属性作为条件进行删除,查询条件使用等号
方法: int deleteByPrimaryKey(Object key); 说明:根据主键字段进行删除,方法参数必须包含完整的主键属性
Example方法 方法: List<T> selectByExample(Object example); 说明:根据Example条件进行查询 重点:这
个查询支持通过 Example 类指定查询列,通过 selectProperties 方法指定查询列
方法: int selectCountByExample(Object example); 说明:根据Example条件进行查询总数
方法: int updateByExample(@Param("record") T record, @Param("example") Object example); 说明:根据
Example条件更新实体 record 包含的全部属性,null值会被更新
方法: int updateByExampleSelective(@Param("record") T record, @Param("example") Object example); 说
明:根据Example条件更新实体 record 包含的不是null的属性值
方法: int deleteByExample(Object example); 说明:根据Example条件删除数据
5.扩展复杂语句查询
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lxs.demo.dao.UserMapper">
<select id="findByUser" resultType="user">
SELECT
*
FROM
tb_user
<where>
<if test="name != null">
name like '%${name}%'
</if>
<if test="note != null">
and note like '%${note}%'
</if>
</where>
</select>
</mapper>