mybatis 的常用注解说明
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
使用注解实现单表CRUD
一、在主配置文件中配置dao
<mappers>
<package name="com.tubai.dao"/>
</mappers>
二、编写实体类
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
public User() {
}
public User(Integer id, String username, String address, String sex, Date birthday) {
this.id = id;
this.username = username;
this.address = address;
this.sex = sex;
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
三、编写dao接口
package com.tubai.dao;
import com.tubai.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* 在Mybaits中针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface UserDao {
//当只有一个value需要赋值的 时候 value可以省略
@Select(value="select * from user")
List<User> selectAll();
@Insert("insert into user(username,birthday,address,sex) values(#{username},#{birthday},#{address},#{sex})")
void saveUser(User user);
@Update("update user set username=#{username},address=#{address} where id = #{id}")
void updateUser(User user);
@Delete("delete from user where id = #{id}")
void deleteUser(Integer id);
@Select("select * from user where id = #{id}")
User selectByID(Integer id);
/**
* 根据名字模糊查询
* 这个使用方法与我们之前在xml中写的是一样的
* 同样分为字符串拼接和PrepareStatement两种
* @param name
* @return
*/
@Select("select * from user where username like #{name}")
List<User> selectByName(String name);
@Select("select count(*) from user")
int selectTotal();
}
因为注解开发不需要写xml配置文件 直接将sql语句写在方法上面即可