【mybatis---5MyBatis注解开发】

MyBatis注解开发
注解方式比较简单,但是实际开发不推荐使用注解,使用配置文件的方式,不需要改源代码。

@Insert:添加
@Update:修改
@Delete:删除
@Select:查询
@Result:实现结果集封装
@Results:可以和@Result一起使用,封装多个结果集
@One:实现一对一和多对一的结果集封装
@Many:实现一对多结果级封装

一、使用注解完成CRUD

  1. SqlMapConfig.xml配置文件

  2. `

     <!--第二种方式:针对com.qcby.dao包下的所有的接口-->
     <package name="com.qcby.dao"/>
    

3. UserDao接口方法和注解的编写 4.import com.qcby.entity.User;
import org.apache.ibatis.annotations.*;

import javax.jws.soap.SOAPBinding;
import java.util.List;

public interface UserDao {
//查询所有
@Select(“select * from user”)
@Results(id=“userMap”,value = {
@Result(property = “id”,column = “id”),
@Result(property = “username”,column = “username”),
@Result(property = “birthday”,column = “birthday”),
@Result(property = “sex”,column = “sex”),
@Result(property = “address”,column = “address”)
})
public List findAll();

//通过ID查询
@Select("select * from user where id = #{id}")
@ResultMap(value = "userMap")
public User findById(int id);

//增加
@Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
@SelectKey(statement="select last_insert_id()",keyColumn = "id",keyProperty = "id",before =false,resultType =Integer.class)
public int insert(User user);

//更新
@Update("update user set username = #{username},birthday = #{birthday},sex = #{sex},address = #{address} where id = #{id}")
public int update(User user);

//删除
@Delete("delete from user where id = #{id}")
public int delete(int id);

//查询数量
@Select("select count(*) from user")
public int findCount();

//模糊查询
@Select("select * from user where username like #{username}")
public List<User> findByName(String username);

}3. UserTest测试方法的编写 4.public class UserTest {
private InputStream in = null;
private SqlSession session = null;
private UserDao mapper = null;

@Before  //前置通知, 在方法执行之前执行
public void init() throws IOException {
    //加载主配置文件,目的是为了构建SqlSessionFactory对象
    in = Resources.getResourceAsStream("SqlMapConfig.xml");
    //创建SqlSessionFactory对象
    SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
    //通过SqlSessionFactory工厂对象创建SqlSesssion对象
    session = factory.openSession();
    //通过Session创建UserDao接口代理对象
    mapper = session.getMapper(UserDao.class);
}

@After  //@After: 后置通知, 在方法执行之后执行 。
public void destory() throws IOException {
    //释放资源
    session.close();
    in.close();
}

/**
 * 测试查询所有的方法
 */
@Test
public void findAll() throws IOException {
    List<User> users = mapper.findAll();
    for (User user:users) {
        System.out.println(user.toString());
    }
}

@Test
public void findById(){
    User user = mapper.findById(4);
    System.out.println(user.toString());
}

@Test
public void insert(){
    User user = new User();
    user.setSex("女");
    user.setUsername("小美");
    user.setBirthday(new Date());
    user.setAddress("保定");
    int insert = mapper.insert(user);
    session.commit();
    System.out.println(insert);
}


@Test
public void update(){
    User user = new User();
    user.setId(22);
    user.setSex("女");
    user.setUsername("小美");
    user.setBirthday(new Date());
    user.setAddress("上海");
    int insert = mapper.update(user);
    session.commit();
    System.out.println(insert);
}

@Test
public void delete(){
   int delete =  mapper.delete(22);
   session.commit();
    System.out.println(delete);
}

@Test
public void findCount(){
    int count = mapper.findCount();
    session.commit();
    System.out.println(count);
}

@Test
public void findByName(){
    List<User> list  = mapper.findByName("%a%");
    for (User user : list) {
        System.out.println(user);
    }
    session.close();
}

}
`
二、多对一的注解查询
1.多对一立即加载查询
①.StudentDao接口的方法编写

@Select(" SELECT  student.*,teacher.Tname FROM student LEFT JOIN teacher  on student.t_id = teacher.id")
@Results(value = {
        @Result(property = "id",column = "id"),
        @Result(property = "Sname",column = "Sname"),
        @Result(property = "sex",column = "sex"),
        @Result(property = "age",column = "age"),
        @Result(property = "t_id",column = "t_id"),
        @Result(property = "teacher.Tname",column = "Tname")
})
public List<Student> getStudent();

②.进行测试

@Test
public void getStudent(){
    List<Student> student = mapper.getStudent();
    for (Student student1:student) {
        System.out.println(student1.toString());
    }
}

2.多对一延迟加载查询
①.StudentDao接口的方法编写

@Select("select * from student")
@Results(value = {
        @Result(property = "id",column = "id"),
        @Result(property = "Sname",column = "Sname"),
        @Result(property = "sex",column = "sex"),
        @Result(property = "age",column = "age"),
        @Result(property = "teacher",column = "t_id",one=@One(select = "com.qcby.dao.TeacherDao.getTeacher",fetchType = FetchType.LAZY))
})
public List<Student> getStudent();

②.TeacherDao接口的方法编写
@Select("select * from teacher where id = #{t_id}") Teacher getTeacher(Integer id);
③.进行测试

@Test
public void getStudent(){
    List<Student> student = mapper.getStudent();
    for (Student student1:student) {
        System.out.println(student1.toString());
    }
}

三、一对多的注解查询
一对多查询,使用延迟加载的方式查询
①.TeacherDao接口的方法编写

//查询所有延迟加载
@Select("select * from Teacher")
@Results(value = {
        @Result(property = "id",column = "id"),
        @Result(property = "Tname",column = "Tname"),
        @Result(property = "students",column = "id",many =@Many(select = "com.qcby.dao.StudentDao.findByUid",fetchType = FetchType.LAZY))
})
public List<Teacher> findAllLazy();

②.StudentDao接口的方法编写

@Select("select * from student where t_id = #{t_id}")
public Teacher findByUid(int uid);

③.进行测试

@Test
public void findAllLazy(){
    List<Teacher> list =  mapper.findAllLazy();
    for (Teacher teacher: list) {
        System.out.println(teacher.toString());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis-Plus支持注解形式的SQL开发。可以在Mapper接口的方法上使用注解来定义SQL语句。以下是一些常用的注解: 1. @Select: 用于查询语句,指定要执行的SQL语句。 2. @Insert: 用于插入语句,指定要执行的SQL语句。 3. @Update: 用于更新语句,指定要执行的SQL语句。 4. @Delete: 用于删除语句,指定要执行的SQL语句。 5. @Param: 用于指定参数的名称,可以在SQL语句中引用这些参数。 同时,Mybatis-Plus还支持使用@TableName注解来指定实体类与数据库表的映射关系,使用@TableField注解来指定实体类属性与数据库表字段的映射关系。 使用注解形式的SQL开发可以简化代码,提高开发效率。可以根据需要选择合适的注解来编写SQL语句,实现增删改查等操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [【SpringBoot】整合Mybatis-Plus并输出SQL日志](https://blog.csdn.net/friendlytkyj/article/details/130915860)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [springboot+shiro+mybatis-plus纯净版框架(附带所需数据库sql)](https://download.csdn.net/download/u011066516/12182453)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值