Mybatis的注解开发学习笔记

avatar
作者
筋斗云
阅读量:0

学习视频: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表

package com.it.pojo;  public class Product    {     private int id;     private String goodsname;     private int price;     private int typeid;      @Override     public String toString() {         return "Product{" +                 "id=" + id +                 ", goodsname='" + goodsname + '\'' +                 ", price=" + price +                 ", typeid=" + typeid +                 '}';     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getGoodsname() {         return goodsname;     }      public void setGoodsname(String goodsname) {         this.goodsname = goodsname;     }      public int getPrice() {         return price;     }      public void setPrice(int price) {         this.price = price;     }      public int getTypeid() {         return typeid;     }      public void setTypeid(int typeid) {         this.typeid = typeid;     } } 
package com.it.dao;  import com.it.pojo.Product; import org.apache.ibatis.annotations.Select;  public interface ProductMapper {     @Select("select  * from product where id=#{id}")     public Product findProductById(int id);  } 

package com.it.dao;  import com.it.pojo.Product; import com.it.utils.MyBatisUtils; import junit.framework.TestCase; import org.junit.Before;  import org.apache.ibatis.session.SqlSession; import org.junit.After; import org.junit.Test;  public class ProductMapperTest extends TestCase {     private ProductMapper productMapper;     private SqlSession session;      @Before     public void setUp()     {         session= MyBatisUtils.getSession();        productMapper=session.getMapper(ProductMapper.class);     }     @Test     public void testFindProductById() {       Product product= productMapper.findProductById(1);         System.out.println(product);      }      @After     public void release()     {         session.close();     }   }


1.2Insert注解

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


1.3Update注解

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


1.4Delete注解

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


1.5Param注解

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


2.基于注解的关联查询

        2.1一对一查询

package com.it.pojo;  public class IdCard {     private int id;     private String code;      @Override     public String toString() {         return "IdCard{" +                 "id=" + id +                 ", code='" + code + '\'' +                 '}';     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getCode() {         return code;     }      public void setCode(String code) {         this.code = code;     } } 
package com.it.pojo;  public class Person {     private int id;     private String name;     private int age;     private String sex;     private IdCard card;      @Override     public String toString() {         return "Person{" +                 "id=" + id +                 ", name='" + name + '\'' +                 ", age=" + age +                 ", sex='" + sex + '\'' +                 ", card=" + card +                 '}';     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public int getAge() {         return age;     }      public void setAge(int age) {         this.age = age;     }      public String getSex() {         return sex;     }      public void setSex(String sex) {         this.sex = sex;     }      public IdCard getCard() {         return card;     }      public void setCard(IdCard card) {         this.card = card;     } } 
package com.it.dao;  import com.it.pojo.IdCard; import org.apache.ibatis.annotations.Select;  public interface IdCardMapper {      @Select("select * from tb_idcard where id=#{id}")      IdCard selectIdCardById(int id);  } 
 public interface PersonMapper {      @Select("select * from tb_person where id=#{id}")     @Results({@Result(                     column = "card_id",                     property = "card",                     one=@One(select = "com.it.dao.IdCardMapper.selectIdCardById")     )})     Person selectPersonById(int id);  } 
public class PersonMapperTest extends TestCase  {      private PersonMapper personMapper;     private SqlSession session;      @Before     public void setUp()     {         session= MyBatisUtils.getSession();         personMapper=session.getMapper(PersonMapper.class);     }     @Test     public void testSelectPersonById() {        Person person=personMapper.selectPersonById(1);           System.out.println(person.toString());       }      @After     public void release()     {         session.close();     } }

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


2.2一对多查询

 public class Orders {     private int id;     private String number;     private int userId;      @Override     public String toString() {         return "Orders{" +                 "id=" + id +                 ", number='" + number + '\'' +                 ", userId=" + userId +                 '}';     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getNumber() {         return number;     }      public void setNumber(String number) {         this.number = number;     }      public int getUserId() {         return userId;     }      public void setUserId(int userId) {         this.userId = userId;     } } 
public class Users {     private int id;     private String username;     private String address;     private List<Orders> ordersList;      @Override     public String toString() {         return "Users{" +                 "id=" + id +                 ", username='" + username + '\'' +                 ", address='" + address + '\'' +                 ", ordersList=" + ordersList +                 '}';     }      public int getId() {         return id;     }      public void setId(int 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 interface OrdersMapper {        @Select("select * from tb_orders where user_id =#{id}")     @Results({             @Result(id = true,property = "id",column = "id"),             @Result(property = "number",column = "number")     })     public List<Orders> selectOrdersByUserId(int id);   } 
public interface UsersMapper {       @Select("select * from tb_user where id=#{id}")     @Results({             @Result(id = true,property = "id",column = "id"),             @Result(property = "username",column = "username"),             @Result(property = "address",column = "address"),             @Result(                     property = "ordersList",                     column = "id",many = @Many(select = "com.it.dao.OrdersMapper.selectOrdersByUserId")             )      })     public Users selectUserById(int id);  } 
public class UsersMapperTest {      @Test     public void testSelectUserById() {         SqlSession session= MyBatisUtils.getSession();         UsersMapper usersMapper = session.getMapper(UsersMapper.class);     Users users= usersMapper.selectUserById(1);         System.out.println(users);         session.close();       } }


2.3多对多查询

public class Orders {     private int id;     private String number;     private int userId;     private List<Product2>product2List;      @Override     public String toString() {         return "Orders{" +                 "id=" + id +                 ", number='" + number + '\'' +                 ", userId=" + userId +                 ", product2List=" + product2List +                 '}';     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getNumber() {         return number;     }      public void setNumber(String number) {         this.number = number;     }      public int getUserId() {         return userId;     }      public void setUserId(int userId) {         this.userId = userId;     } } 
import java.util.List;  public class Product2 {     private int id;     private String name;     private double price;     private List<Orders>ordersList;      @Override     public String toString() {         return "Product2{" +                 "id=" + id +                 ", name='" + name + '\'' +                 ", price=" + price +                 ", ordersList=" + ordersList +                 '}';     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public double getPrice() {         return price;     }      public void setPrice(double price) {         this.price = price;     }      public List<Orders> getOrdersList() {         return ordersList;     }      public void setOrdersList(List<Orders> ordersList) {         this.ordersList = ordersList;     } } 
public interface Product2Mapper {       @Select("select * from tb_product where id in"+"(select product_id from tb_ordersitem where orders_id=#{orderId})")     public List<Product2> selectProduct2sByOrdersId(int orderId);  } 
    @Select("select  * from tb_orders where id=#{id}")     @Results(             {              @Result(id = true,column = "id",property = "id"),              @Result(column = "number",property = "number"),              @Result(                      property = "product2List",                      column = "id",                      many = @Many(select = "com.it.dao.Product2Mapper.selectProduct2sByOrdersId")              )             }     )     public Orders selectOrdersById(int id); 
public class OrdersMapperTest extends TestCase {      public void testSelectOrdersById() {         SqlSession session= MyBatisUtils.getSession();         OrdersMapper ordersMapper = session.getMapper(OrdersMapper.class);          Orders orders = ordersMapper.selectOrdersById(1);          System.out.println(orders);         session.close();      } }


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

数据准备

CREATE TABLE student( 	id INT PRIMARY KEY AUTO_INCREMENT, 	NAME VARCHAR(20), 	age INT, 	cid INT ); INSERT INTO student VALUES(1,'张三',18,1); INSERT INTO student VALUES(2,'李四',18,2); INSERT INTO student VALUES(3,'王五',19,2); INSERT INTO student VALUES(4,'赵六',20,1);  CREATE TABLE class( 	id INT PRIMARY KEY AUTO_INCREMENT, 	classname VARCHAR(20) ); INSERT INTO class VALUES(1,'一班'); INSERT INTO class VALUES(2,'二班');    
 public class Student {     private int id;     private  String name;     private  int age;     private  int cid;      @Override     public String toString() {         return "Student{" +                 "id=" + id +                 ", name='" + name + '\'' +                 ", age=" + age +                 ", cid=" + cid +                 '}';     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public int getAge() {         return age;     }      public void setAge(int age) {         this.age = age;     }      public int getCid() {         return cid;     }      public void setCid(int cid) {         this.cid = cid;     } } 
public class Iclass {     private int id;     private String classname;     //一对多映射     private List<Student>studentList;      @Override     public String toString() {         return "Iclass{" +                 "id=" + id +                 ", classname='" + classname + '\'' +                 ", studentList=" + studentList +                 '}';     }      public String getClassname() {         return classname;     }      public void setClassname(String classname) {         this.classname = classname;     }      public int getId() {         return id;     }      public void setId(int id) {         this.id = id;     }      public List<Student> getStudentList() {         return studentList;     }      public void setStudentList(List<Student> studentList) {         this.studentList = studentList;     } } 

查询id为2的学生信息 

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


修改学生信息

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


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

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!