mybatis注解实现增删改查,一对一等映射和sql动态查询

文章目录

  • mybatis常用注解
  • mybatis注解增删改查
  • mybatis一对一、一对多、多对多操作
    • 一对一
    • 一对多
    • 多对多
  • mybatis动态sql注解

mybatis常用注解

mybatis注解实现增删改查,一对一等映射和sql动态查询_第1张图片
mybatis注解实现增删改查,一对一等映射和sql动态查询_第2张图片

mybatis注解增删改查

UserMapper.java

package org.fkit.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.fkit.domain.User;

public interface UserMapper {
	
	@Insert("INSERT INTO TB_USER(name,sex,age) VALUES(#{name},#{sex},#{age})")
	@Options(useGeneratedKeys=true,keyProperty="id")
//	@SelectKey(before=false,keyProperty="id",resultType=Integer.class,
//	statement="SELECT LAST_INSERT_ID() AS id")
	int saveUser(User user);
	
	@Delete("DELETE FROM TB_USER WHERE id = #{id}")
	int removeUser(@Param("id") Integer id);
	
	@Update("UPDATE TB_USER SET name = #{name},sex = #{sex},age = #{age} WHERE id = #{id}")
	void modifyUser(User user);
	
	@Select("SELECT * FROM TB_USER WHERE id = #{id}")
	@Results({
		@Result(id=true,column="id",property="id"),
		@Result(column="name",property="name"),
		@Result(column="sex",property="sex"),
		@Result(column="age",property="age")
	})
	User selectUserById(@Param("id") Integer id);
	
	@Select("SELECT * FROM TB_USER ")
	List selectAllUser();

}

saveUser方法
在这里插入图片描述
执行selectUser方法
在这里插入图片描述
运行removeUser方法
在这里插入图片描述

mybatis一对一、一对多、多对多操作

一对一

Card.java

package org.fkit.domain;

import java.io.Serializable;

public class Card implements Serializable {
	
	private Integer id;  // 主键id
	private String code; // 身份证编号
	
	public Card() {
		super();
		// TODO Auto-generated constructor stub
	}
	省略getter和setter方法

}

Person.java

public class Person implements Serializable {

	private Integer id;  // 主键id
	private String name; // 姓名
	private String sex;  // 性别
	private Integer age; // 年龄
	
	// 人和身份证是一对一的关系,即一个人只有一个身份证
	private Card card; 

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

	省略getter和setter方法
	
	
	
}

PersonMapper.java

package org.fkit.mapper;

import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.fkit.domain.Person;

public interface PersonMapper {
	
	@Select("SELECT * FROM TB_PERSON WHERE ID = #{id}")
	@Results({
		@Result(id=true,column="id",property="id"),
		@Result(column="name",property="name"),
		@Result(column="sex",property="sex"),
		@Result(column="age",property="age"),
		@Result(column="card_id",property="card",
		one=@One(
				select="org.fkit.mapper.CardMapper.selectCardById",
				fetchType=FetchType.EAGER))
	})
	Person selectPersonById(Integer id);

}

CardMapper.java

package org.fkit.mapper;

import org.apache.ibatis.annotations.Select;
import org.fkit.domain.Card;

public interface CardMapper {

	@Select("SELECT * FROM TB_CARD WHERE ID = #{id} ")
	Card selectCardById(Integer id);
	
}

mybatis注解实现增删改查,一对一等映射和sql动态查询_第3张图片

一对多

clazz.java

package org.fkit.domain;

import java.io.Serializable;
import java.util.List;

public class Clazz implements Serializable {
	
	private Integer id; // 班级id,主键
	private String code; // 班级编号
	private String name; // 班级名称
	
	// 班级和学生是一对多的关系,即一个班级可以有多个学生
	private List students;
	
	public Clazz() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	省略getter和setter方法

}

Student.java

public class Student implements Serializable {

	private Integer id; // 学生id,主键
	private String name; // 姓名
	private String sex;  // 性别
	private Integer age; // 年龄
	
	// 学生和班级是多对一的关系,即一个学生只属于一个班级
	private Clazz clazz;

	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	省略getter和setter

	
}

ClassMapper.java

package org.fkit.mapper;


import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.fkit.domain.Clazz;

public interface ClazzMapper {

	// 根据id查询班级信息
	@Select("SELECT * FROM TB_CLAZZ  WHERE ID = #{id}")
	@Results({
		@Result(id=true,column="id",property="id"),
		@Result(column="code",property="code"),
		@Result(column="name",property="name"),
		@Result(column="id",property="students",
		many=@Many(
				select="org.fkit.mapper.StudentMapper.selectByClazzId",
				fetchType=FetchType.LAZY))
	})
	Clazz selectById(Integer id);

		
}

StudentMapper.java

package org.fkit.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.fkit.domain.Student;

public interface StudentMapper {
	
	// 根据班级id查询班级所有学生
	@Select("SELECT * FROM TB_STUDENT WHERE CLAZZ_ID = #{id}")
	@Results({
		@Result(id=true,column="id",property="id"),
		@Result(column="name",property="name"),
		@Result(column="sex",property="sex"),
		@Result(column="age",property="age")
	})
	List selectByClazzId(Integer clazz_id);
		
}

多对多

Article.java

package org.fkit.domain;

import java.io.Serializable;
import java.util.List;

public class Article implements Serializable {
	
	private Integer id;		// 商品id,主键
	private String name;	// 商品名称
	private Double price;	// 商品价格
	private String remark;	// 商品描述
	
	// 商品和订单是多对多的关系,即一种商品可以包含在多个订单中
	private List orders;

	public Article() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Article(String name, Double price, String remark) {
		super();
		this.name = name;
		this.price = price;
		this.remark = remark;
	}
	
	省略getter和setter

}

Order.java

package org.fkit.domain;

import java.io.Serializable;
import java.util.List;

public class Order implements Serializable {

	private Integer id;  // 订单id,主键
	private String code;  // 订单编号
	private Double total; // 订单总金额
	
	// 订单和用户是多对一的关系,即一个订单只属于一个用户
	private User user;
	
	// 订单和商品是多对多的关系,即一个订单可以包含多种商品
	private List
articles; public Order() { super(); // TODO Auto-generated constructor stub } 省略getter和setter }

User.java

public class User implements Serializable{
	
	private Integer id;  // 用户id,主键
	private String username;  // 用户名
	private String loginname; // 登录名
	private String password;  // 密码
	private String phone;    // 联系电话
	private String address;  // 收货地址
	
	// 用户和订单是一对多的关系,即一个用户可以有多个订单
	private List orders;

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}

	public User(String username, String loginname, String password,
			String phone, String address) {
		super();
		this.username = username;
		this.loginname = loginname;
		this.password = password;
		this.phone = phone;
		this.address = address;
	}

	省略getter和setter


}

UserMapper.java

package org.fkit.mapper;

import org.apache.ibatis.annotations.Select;
import org.fkit.domain.User;

public interface UserMapper {

	@Select("SELECT * FROM TB_USER WHERE ID = #{id} ")
	User selectById(Integer id);
	
}

OrderMapper.java

package org.fkit.mapper;


import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;
import org.fkit.domain.Order;

public interface OrderMapper {

	@Select("SELECT * FROM TB_ORDER WHERE ID = #{id}")
	@Results({
		@Result(id=true,column="id",property="id"),
		@Result(column="code",property="code"),
		@Result(column="total",property="total"),
		@Result(column="user_id",property="user",
			one=@One(select="org.fkit.mapper.UserMapper.selectById",
		fetchType=FetchType.EAGER)),
		@Result(column="id",property="articles",
			many=@Many(select="org.fkit.mapper.ArticleMapper.selectByOrderId",
		fetchType=FetchType.LAZY))
	})
	Order selectById(Integer id);
	
}

ArticleMapper.java

package org.fkit.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;
import org.fkit.domain.Article;

public interface ArticleMapper {

	@Select("SELECT * FROM tb_article WHERE id IN (SELECT article_id FROM tb_item WHERE order_id = #{id} ) ")
	List
selectByOrderId(Integer order_id); }

mybatis动态sql注解

EmployeeMapper.java

package org.fkit.mapper;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import org.fkit.domain.Employee;

public interface EmployeeMapper {
	
	// 动态查询
	@SelectProvider(type=EmployeeDynaSqlProvider.class,method="selectWhitParam")
	List selectWhitParam(Map param);
	
	// 动态插入
	@InsertProvider(type=EmployeeDynaSqlProvider.class,method="insertEmployee")
	@Options(useGeneratedKeys = true, keyProperty = "id")  
	int insertEmployee(Employee employee);
	
	// 根据id查询
	@SelectProvider(type=EmployeeDynaSqlProvider.class,method="selectWhitParam")
	Employee selectEmployeeWithId(Map param);
	
	// 动态更新
	@UpdateProvider(type=EmployeeDynaSqlProvider.class,method="updateEmployee")
	void updateEmployee(Employee employee);

	// 动态删除
	@DeleteProvider(type=EmployeeDynaSqlProvider.class,method="deleteEmployee")
	void deleteEmployee(Map param);
	
}

EmployeeDynaSqlProvider.java

package org.fkit.mapper;


import java.util.Map;

import org.apache.ibatis.jdbc.SQL;
import org.fkit.domain.Employee;

public class EmployeeDynaSqlProvider {
	
	public String selectWhitParam(Map param){
		return new SQL(){
			{
				SELECT("*");
				FROM("tb_employee");
				if(param.get("id") != null){
					WHERE(" id = #{id} ");
				}
				if(param.get("loginname") != null){
					WHERE(" loginname = #{loginname} ");
				}
				if(param.get("password") != null){
					WHERE("password = #{password}");
				}
				if(param.get("name")!= null){
					WHERE("name = #{name}");
				}
				if(param.get("sex")!= null){
					WHERE("sex = #{sex}");
				}
				if(param.get("age")!= null){
					WHERE("age = #{age}");
				}
				if(param.get("phone")!= null){
					WHERE("phone = #{phone}");
				}
				if(param.get("sal")!= null){
					WHERE("sal = #{sal}");
				}
				if(param.get("state")!= null){
					WHERE("state = #{state}");
				}
				
			}
		}.toString();
	}	
	
	public String insertEmployee(Employee employee){
		
		return new SQL(){
			{
				INSERT_INTO("tb_employee");
				if(employee.getLoginname() != null){
					VALUES("loginname", "#{loginname}");
				}
				if(employee.getPassword() != null){
					VALUES("password", "#{password}");
				}
				if(employee.getName()!= null){
					VALUES("name", "#{name}");
				}
				if(employee.getSex()!= null){
					VALUES("sex", "#{sex}");
				}
				if(employee.getAge()!= null){
					VALUES("age", "#{age}");
				}
				if(employee.getPhone()!= null){
					VALUES("phone", "#{phone}");
				}
				if(employee.getSal()!= null){
					VALUES("sal", "#{sal}");
				}
				if(employee.getState()!= null){
					VALUES("state", "#{state}");
				}
			}
		}.toString();
	}
	
	public String updateEmployee(Employee employee){
		
		return new SQL(){
			{
				UPDATE("tb_employee");
				if(employee.getLoginname() != null){
					SET("loginname = #{loginname}");
				}
				if(employee.getPassword() != null){
					SET("password = #{password}");
				}
				if(employee.getName()!= null){
					SET("name = #{name}");
				}
				if(employee.getSex()!= null){
					SET("sex = #{sex}");
				}
				if(employee.getAge()!= null){
					SET("age = #{age}");
				}
				if(employee.getPhone()!= null){
					SET("phone = #{phone}");
				}
				if(employee.getSal()!= null){
					SET("sal = #{sal}");
				}
				if(employee.getState()!= null){
					SET("state = #{state}");
				}
				WHERE(" id = #{id} ");
			}
		}.toString();
	}
	
	public String deleteEmployee(Map param){
		
		return new SQL(){
			{
				DELETE_FROM("tb_employee");
				if(param.get("id") != null){
					WHERE(" id = #{id} ");
				}
				if(param.get("loginname") != null){
					WHERE(" loginname = #{loginname} ");
				}
				if(param.get("password") != null){
					WHERE("password = #{password}");
				}
				if(param.get("name")!= null){
					WHERE("name = #{name}");
				}
				if(param.get("sex")!= null){
					WHERE("sex = #{sex}");
				}
				if(param.get("age")!= null){
					WHERE("age = #{age}");
				}
				if(param.get("phone")!= null){
					WHERE("phone = #{phone}");
				}
				if(param.get("sal")!= null){
					WHERE("sal = #{sal}");
				}
				if(param.get("state")!= null){
					WHERE("state = #{state}");
				}
			}
		}.toString();
	}

	
	
}

public class Employee implements Serializable {
	
	private Integer id;			 // 主键id
	private String loginname;	 // 登录名
	private String password;	 // 密码
	private String name;		 // 真实姓名
	private String sex;			 // 性别
	private Integer age;		 // 年龄
	private String phone;		 // 电话
	private Double sal;		     // 薪水
	private String state;	 	 // 状态
	
	public Employee() {
		super();
		// TODO Auto-generated constructor stub
	}
	省略getter和setter方法

}

你可能感兴趣的:(mybatis注解实现增删改查,一对一等映射和sql动态查询)