当前位置:   article > 正文

Mybatis的注解开发学习笔记

Mybatis的注解开发学习笔记

学习视频:5001 @Select注解_哔哩哔哩_bilibili~5009 案例:基于MyBatis注解的学生管理程序_哔哩哔哩_bilibili

目录

1.基于注解的单表增删改查

        1.1@Select注解

1.2Insert注解

1.3Update注解

1.4Delete注解

1.5Param注解

2.基于注解的关联查询

        2.1一对一查询

2.2一对多查询

2.3多对多查询

3.基于MyBatis注解的学生管理程序

查询id为2的学生信息 

修改学生信息

一对多查询班级为二班的学生


1.基于注解的单表增删改查

        1.1@Select注解

数据准备

product表

  1. package com.it.pojo;
  2. public class Product {
  3. private int id;
  4. private String goodsname;
  5. private int price;
  6. private int typeid;
  7. @Override
  8. public String toString() {
  9. return "Product{" +
  10. "id=" + id +
  11. ", goodsname='" + goodsname + '\'' +
  12. ", price=" + price +
  13. ", typeid=" + typeid +
  14. '}';
  15. }
  16. public int getId() {
  17. return id;
  18. }
  19. public void setId(int id) {
  20. this.id = id;
  21. }
  22. public String getGoodsname() {
  23. return goodsname;
  24. }
  25. public void setGoodsname(String goodsname) {
  26. this.goodsname = goodsname;
  27. }
  28. public int getPrice() {
  29. return price;
  30. }
  31. public void setPrice(int price) {
  32. this.price = price;
  33. }
  34. public int getTypeid() {
  35. return typeid;
  36. }
  37. public void setTypeid(int typeid) {
  38. this.typeid = typeid;
  39. }
  40. }
  1. package com.it.dao;
  2. import com.it.pojo.Product;
  3. import org.apache.ibatis.annotations.Select;
  4. public interface ProductMapper {
  5. @Select("select * from product where id=#{id}")
  6. public Product findProductById(int id);
  7. }

  1. package com.it.dao;
  2. import com.it.pojo.Product;
  3. import com.it.utils.MyBatisUtils;
  4. import junit.framework.TestCase;
  5. import org.junit.Before;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.junit.After;
  8. import org.junit.Test;
  9. public class ProductMapperTest extends TestCase {
  10. private ProductMapper productMapper;
  11. private SqlSession session;
  12. @Before
  13. public void setUp()
  14. {
  15. session= MyBatisUtils.getSession();
  16. productMapper=session.getMapper(ProductMapper.class);
  17. }
  18. @Test
  19. public void testFindProductById() {
  20. Product product= productMapper.findProductById(1);
  21. System.out.println(product);
  22. }
  23. @After
  24. public void release()
  25. {
  26. session.close();
  27. }
  28. }


1.2Insert注解

  1. @Insert("insert into product(goodsname,price,typeid) values (#{goodsname},#{price},#{typeid})")
  2. public int insertProduct(Product product);
  1. @Test
  2. public void testinsertProduct()
  3. {
  4. Product product2=new Product();
  5. product2.setGoodsname("风扇");
  6. product2.setPrice(200);
  7. product2.setTypeid(2);
  8. int i= productMapper.insertProduct(product2);
  9. System.out.println(i);
  10. session.commit();
  11. }


1.3Update注解

  1. @Update("update product set goodsname=#{goodsname},price=#{price} where id=#{id}")
  2. public int updateProduct(Product product);
  1. @Test
  2. public void testupdateProduct()
  3. {
  4. Product product2=new Product();
  5. product2.setGoodsname("大风扇");
  6. product2.setId(5);
  7. product2.setPrice(300);
  8. int i= productMapper.updateProduct(product2);
  9. System.out.println(i);
  10. session.commit();
  11. }


1.4Delete注解

  1. @Delete("delete from product where id=#{id}")
  2. public int deleteProduct(int id);
  1. @Test
  2. public void testdeleteProduct()
  3. {
  4. int i= productMapper.deleteProduct(5);
  5. if (i>0)
  6. {
  7. System.out.println("删除成功");
  8. }
  9. session.commit();
  10. }


1.5Param注解

  1. @Select("select * from product where id=#{param01} and goodsname=#{param02}")
  2. public Product selectProductByIdAndGoodsname(@Param("param01") int id,
  3. @Param("param02") String goodsname);
  1. @Test
  2. public void testselectProductByIdAndGoodsname()
  3. {
  4. Product product=productMapper.selectProductByIdAndGoodsname(1,"电视机");
  5. System.out.println(product);
  6. }


2.基于注解的关联查询

        2.1一对一查询

  1. package com.it.pojo;
  2. public class IdCard {
  3. private int id;
  4. private String code;
  5. @Override
  6. public String toString() {
  7. return "IdCard{" +
  8. "id=" + id +
  9. ", code='" + code + '\'' +
  10. '}';
  11. }
  12. public int getId() {
  13. return id;
  14. }
  15. public void setId(int id) {
  16. this.id = id;
  17. }
  18. public String getCode() {
  19. return code;
  20. }
  21. public void setCode(String code) {
  22. this.code = code;
  23. }
  24. }
  1. package com.it.pojo;
  2. public class Person {
  3. private int id;
  4. private String name;
  5. private int age;
  6. private String sex;
  7. private IdCard card;
  8. @Override
  9. public String toString() {
  10. return "Person{" +
  11. "id=" + id +
  12. ", name='" + name + '\'' +
  13. ", age=" + age +
  14. ", sex='" + sex + '\'' +
  15. ", card=" + card +
  16. '}';
  17. }
  18. public int getId() {
  19. return id;
  20. }
  21. public void setId(int id) {
  22. this.id = id;
  23. }
  24. public String getName() {
  25. return name;
  26. }
  27. public void setName(String name) {
  28. this.name = name;
  29. }
  30. public int getAge() {
  31. return age;
  32. }
  33. public void setAge(int age) {
  34. this.age = age;
  35. }
  36. public String getSex() {
  37. return sex;
  38. }
  39. public void setSex(String sex) {
  40. this.sex = sex;
  41. }
  42. public IdCard getCard() {
  43. return card;
  44. }
  45. public void setCard(IdCard card) {
  46. this.card = card;
  47. }
  48. }
  1. package com.it.dao;
  2. import com.it.pojo.IdCard;
  3. import org.apache.ibatis.annotations.Select;
  4. public interface IdCardMapper {
  5. @Select("select * from tb_idcard where id=#{id}")
  6. IdCard selectIdCardById(int id);
  7. }
  1. public interface PersonMapper {
  2. @Select("select * from tb_person where id=#{id}")
  3. @Results({@Result(
  4. column = "card_id",
  5. property = "card",
  6. one=@One(select = "com.it.dao.IdCardMapper.selectIdCardById")
  7. )})
  8. Person selectPersonById(int id);
  9. }
  1. public class PersonMapperTest extends TestCase {
  2. private PersonMapper personMapper;
  3. private SqlSession session;
  4. @Before
  5. public void setUp()
  6. {
  7. session= MyBatisUtils.getSession();
  8. personMapper=session.getMapper(PersonMapper.class);
  9. }
  10. @Test
  11. public void testSelectPersonById() {
  12. Person person=personMapper.selectPersonById(1);
  13. System.out.println(person.toString());
  14. }
  15. @After
  16. public void release()
  17. {
  18. session.close();
  19. }
  20. }

这里将mybatis版本改为了3.5.3,不然报错 


2.2一对多查询

  1. public class Orders {
  2. private int id;
  3. private String number;
  4. private int userId;
  5. @Override
  6. public String toString() {
  7. return "Orders{" +
  8. "id=" + id +
  9. ", number='" + number + '\'' +
  10. ", userId=" + userId +
  11. '}';
  12. }
  13. public int getId() {
  14. return id;
  15. }
  16. public void setId(int id) {
  17. this.id = id;
  18. }
  19. public String getNumber() {
  20. return number;
  21. }
  22. public void setNumber(String number) {
  23. this.number = number;
  24. }
  25. public int getUserId() {
  26. return userId;
  27. }
  28. public void setUserId(int userId) {
  29. this.userId = userId;
  30. }
  31. }
  1. public class Users {
  2. private int id;
  3. private String username;
  4. private String address;
  5. private List<Orders> ordersList;
  6. @Override
  7. public String toString() {
  8. return "Users{" +
  9. "id=" + id +
  10. ", username='" + username + '\'' +
  11. ", address='" + address + '\'' +
  12. ", ordersList=" + ordersList +
  13. '}';
  14. }
  15. public int getId() {
  16. return id;
  17. }
  18. public void setId(int id) {
  19. this.id = id;
  20. }
  21. public String getUsername() {
  22. return username;
  23. }
  24. public void setUsername(String username) {
  25. this.username = username;
  26. }
  27. public String getAddress() {
  28. return address;
  29. }
  30. public void setAddress(String address) {
  31. this.address = address;
  32. }
  33. }
  1. public interface OrdersMapper {
  2. @Select("select * from tb_orders where user_id =#{id}")
  3. @Results({
  4. @Result(id = true,property = "id",column = "id"),
  5. @Result(property = "number",column = "number")
  6. })
  7. public List<Orders> selectOrdersByUserId(int id);
  8. }
  1. public interface UsersMapper {
  2. @Select("select * from tb_user where id=#{id}")
  3. @Results({
  4. @Result(id = true,property = "id",column = "id"),
  5. @Result(property = "username",column = "username"),
  6. @Result(property = "address",column = "address"),
  7. @Result(
  8. property = "ordersList",
  9. column = "id",many = @Many(select = "com.it.dao.OrdersMapper.selectOrdersByUserId")
  10. )
  11. })
  12. public Users selectUserById(int id);
  13. }
  1. public class UsersMapperTest {
  2. @Test
  3. public void testSelectUserById() {
  4. SqlSession session= MyBatisUtils.getSession();
  5. UsersMapper usersMapper = session.getMapper(UsersMapper.class);
  6. Users users= usersMapper.selectUserById(1);
  7. System.out.println(users);
  8. session.close();
  9. }
  10. }


2.3多对多查询

  1. public class Orders {
  2. private int id;
  3. private String number;
  4. private int userId;
  5. private List<Product2>product2List;
  6. @Override
  7. public String toString() {
  8. return "Orders{" +
  9. "id=" + id +
  10. ", number='" + number + '\'' +
  11. ", userId=" + userId +
  12. ", product2List=" + product2List +
  13. '}';
  14. }
  15. public int getId() {
  16. return id;
  17. }
  18. public void setId(int id) {
  19. this.id = id;
  20. }
  21. public String getNumber() {
  22. return number;
  23. }
  24. public void setNumber(String number) {
  25. this.number = number;
  26. }
  27. public int getUserId() {
  28. return userId;
  29. }
  30. public void setUserId(int userId) {
  31. this.userId = userId;
  32. }
  33. }
  1. import java.util.List;
  2. public class Product2 {
  3. private int id;
  4. private String name;
  5. private double price;
  6. private List<Orders>ordersList;
  7. @Override
  8. public String toString() {
  9. return "Product2{" +
  10. "id=" + id +
  11. ", name='" + name + '\'' +
  12. ", price=" + price +
  13. ", ordersList=" + ordersList +
  14. '}';
  15. }
  16. public int getId() {
  17. return id;
  18. }
  19. public void setId(int id) {
  20. this.id = id;
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public double getPrice() {
  29. return price;
  30. }
  31. public void setPrice(double price) {
  32. this.price = price;
  33. }
  34. public List<Orders> getOrdersList() {
  35. return ordersList;
  36. }
  37. public void setOrdersList(List<Orders> ordersList) {
  38. this.ordersList = ordersList;
  39. }
  40. }
  1. public interface Product2Mapper {
  2. @Select("select * from tb_product where id in"+"(select product_id from tb_ordersitem where orders_id=#{orderId})")
  3. public List<Product2> selectProduct2sByOrdersId(int orderId);
  4. }
  1. @Select("select * from tb_orders where id=#{id}")
  2. @Results(
  3. {
  4. @Result(id = true,column = "id",property = "id"),
  5. @Result(column = "number",property = "number"),
  6. @Result(
  7. property = "product2List",
  8. column = "id",
  9. many = @Many(select = "com.it.dao.Product2Mapper.selectProduct2sByOrdersId")
  10. )
  11. }
  12. )
  13. public Orders selectOrdersById(int id);
  1. public class OrdersMapperTest extends TestCase {
  2. public void testSelectOrdersById() {
  3. SqlSession session= MyBatisUtils.getSession();
  4. OrdersMapper ordersMapper = session.getMapper(OrdersMapper.class);
  5. Orders orders = ordersMapper.selectOrdersById(1);
  6. System.out.println(orders);
  7. session.close();
  8. }
  9. }


3.基于MyBatis注解的学生管理程序

数据准备

  1. CREATE TABLE student(
  2. id INT PRIMARY KEY AUTO_INCREMENT,
  3. NAME VARCHAR(20),
  4. age INT,
  5. cid INT
  6. );
  7. INSERT INTO student VALUES(1,'张三',18,1);
  8. INSERT INTO student VALUES(2,'李四',18,2);
  9. INSERT INTO student VALUES(3,'王五',19,2);
  10. INSERT INTO student VALUES(4,'赵六',20,1);
  11. CREATE TABLE class(
  12. id INT PRIMARY KEY AUTO_INCREMENT,
  13. classname VARCHAR(20)
  14. );
  15. INSERT INTO class VALUES(1,'一班');
  16. INSERT INTO class VALUES(2,'二班');
  1. public class Student {
  2. private int id;
  3. private String name;
  4. private int age;
  5. private int cid;
  6. @Override
  7. public String toString() {
  8. return "Student{" +
  9. "id=" + id +
  10. ", name='" + name + '\'' +
  11. ", age=" + age +
  12. ", cid=" + cid +
  13. '}';
  14. }
  15. public int getId() {
  16. return id;
  17. }
  18. public void setId(int id) {
  19. this.id = id;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. public int getAge() {
  28. return age;
  29. }
  30. public void setAge(int age) {
  31. this.age = age;
  32. }
  33. public int getCid() {
  34. return cid;
  35. }
  36. public void setCid(int cid) {
  37. this.cid = cid;
  38. }
  39. }
  1. public class Iclass {
  2. private int id;
  3. private String classname;
  4. //一对多映射
  5. private List<Student>studentList;
  6. @Override
  7. public String toString() {
  8. return "Iclass{" +
  9. "id=" + id +
  10. ", classname='" + classname + '\'' +
  11. ", studentList=" + studentList +
  12. '}';
  13. }
  14. public String getClassname() {
  15. return classname;
  16. }
  17. public void setClassname(String classname) {
  18. this.classname = classname;
  19. }
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26. public List<Student> getStudentList() {
  27. return studentList;
  28. }
  29. public void setStudentList(List<Student> studentList) {
  30. this.studentList = studentList;
  31. }
  32. }

查询id为2的学生信息 

  1. public interface StudentMapper {
  2. @Select("select * from student where id=#{id}")
  3. public Student selectStudentById(int id);
  4. }
  1. public class StudentMapperTest extends TestCase {
  2. public void testSelectStudentById() {
  3. SqlSession session= MyBatisUtils.getSession();
  4. StudentMapper studentMapper= session.getMapper(StudentMapper.class);
  5. Student student= studentMapper.selectStudentById(2);
  6. System.out.println(student);
  7. session.close();
  8. }
  9. }


修改学生信息

  1. @Update("update student set name=#{name},age=#{age} where id=#{id}")
  2. public int updateStudent(Student student);
  1. public void testupdateStudentByName() {
  2. SqlSession session= MyBatisUtils.getSession();
  3. StudentMapper studentMapper= session.getMapper(StudentMapper.class);
  4. Student student= new Student();
  5. student.setName("小吴");
  6. student.setAge(20);
  7. student.setId(4);
  8. int i= studentMapper.updateStudent(student);
  9. if(i>0){
  10. System.out.println("修改成功");
  11. }
  12. session.commit();
  13. session.close();
  14. }


一对多查询班级为二班的学生

  1. @Select("select * from student where cid=#{cid}")
  2. @Results({
  3. @Result(id =true,column = "id",property = "id"),
  4. @Result(column = "name",property = "name"),
  5. @Result(column = "age",property = "age")
  6. })
  7. public List<Student>selectStudentsByCid(int cid);
  1. @Select("select * from class where id=#{id}")
  2. @Results({
  3. @Result(id = true,column = "id",property = "id"),
  4. @Result(property = "classname",column = "classname"),
  5. @Result(property = "studentList",
  6. column = "id",
  7. many =@Many(select = "com.it.dao.StudentMapper.selectStudentsByCid")
  8. )
  9. })
  10. public Iclass selectClassById(int id);
  1. public class ClassMapperTest extends TestCase {
  2. public void testSelectClassById() {
  3. SqlSession session= MyBatisUtils.getSession();
  4. ClassMapper classMapper = session.getMapper(ClassMapper.class);
  5. Iclass iclass =classMapper.selectClassById(2);
  6. System.out.println(iclass);
  7. session.close();
  8. }
  9. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/921868
推荐阅读
相关标签
  

闽ICP备14008679号