转载

MyBatis 中 @One 和 @Many 关联与映射以及阿里云的配置

要求:数据库脚本(上一个博客已经写了),Spring ToolSuite4,以及阿里云数据库,Postman测试工具

1.阿里云的配置 


 更换操作系统:

 


重置实例密码

 


配置安全组规则

 


命令行远程连接阿里云

 


查看运行的程序


官网下载mysql8以及更新软件仓库,

 


 安装mysql8

service mysql install

登录mysql并修改root权限


 


记得一定要退出mysql重启mysql

service mysql restart

 


接下来就可以连接阿里云的数据库了,除了命令行连接,还可以使用MySQL Workbeach 连接*(我的其他博客有提到),有兴趣的小伙伴可以去看看。


2. MyBatis 中 @One 和 @Many 关联与映射

创建一个Spring Boot项目(前面博客具体由提到)

选中这四个


我们这采用的是2.2.5的版本,如果pom.xml出现问题,把版本改为2.2.2即可,如果不行,可以去参考前面写的博客。改版本后记得更新项目

 


连接数据库的配置信息

39.100.23.188是你的阿里云ip公网地址

test是你的hr数据库的密码

一定要确保你的阿里云数据库有hr这个库,没有就新建一个,前面博客有说过如何新建库

spring.datasource.url=jdbc:mysql://39.100.23.188:3306/hr
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

 


data.sql:向hr库中插入数据,方便测试

insert into dept(title,loc) values('产品','北京'), 
('研发','长沙'),('测试','武汉'),('实施','广州');

insert into staff(name,dept_id) values('alice',1);
insert into staff(name,dept_id) values('bob',1);
insert into staff(name,dept_id) values('小王',2);
insert into staff(name,dept_id) values('小李',4);
insert into staff(name,dept_id) values('小张',4);

insert into address(city,street,staff_id,tel) values('长沙','五一路',4,'139');
insert into address(city,street,staff_id,tel) values('长沙','五一路',1,'139');
insert into address(city,street,staff_id,tel) values('长沙','五一路',2,'139');
insert into address(city,street,staff_id,tel) values('长沙','五一路',3,'139');
insert into address(city,street,staff_id,tel) values('永州','鼓楼大街',4,'139');
insert into address(city,street,staff_id,tel) values('湘潭','钟楼大街',1,'139');
insert into address(city,street,staff_id,tel) values('南京','北京西路',2,'139')

hr.sql(数据库表结构)可以利用MySQL Workbeach数据建模


-- MySQL Script generated by MySQL Workbench
-- Tue Mar 31 16:40:38 2020
-- Model: New Model    Version: 1.0
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

-- -----------------------------------------------------
-- Schema hr
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `hr` ;

-- -----------------------------------------------------
-- Schema hr
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `hr` DEFAULT CHARACTER SET utf8 ;
USE `hr` ;

-- -----------------------------------------------------
-- Table `hr`.`dept`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `hr`.`dept` ;

CREATE TABLE IF NOT EXISTS `hr`.`dept` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(45) NOT NULL,
  `loc` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `title_UNIQUE` (`title` ASC) VISIBLE)
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `hr`.`staff`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `hr`.`staff` ;

CREATE TABLE IF NOT EXISTS `hr`.`staff` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NOT NULL,
  `job` VARCHAR(45) NULL,
  `phone` CHAR(11) NULL,
  `dept_id` INT NULL,
  PRIMARY KEY (`id`),
  INDEX `staff_fk_dept_idx` (`dept_id` ASC) VISIBLE,
  CONSTRAINT `staff_fk_dept`
    FOREIGN KEY (`dept_id`)
    REFERENCES `hr`.`dept` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `hr`.`address`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `hr`.`address` ;

CREATE TABLE IF NOT EXISTS `hr`.`address` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `city` VARCHAR(45) NOT NULL,
  `street` VARCHAR(45) NOT NULL,
  `tel` CHAR(11) NOT NULL,
  `staff_id` INT NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `address_fk_staff_idx` (`staff_id` ASC) VISIBLE,
  CONSTRAINT `address_fk_staff`
    FOREIGN KEY (`staff_id`)
    REFERENCES `hr`.`staff` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;


SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


Spring 工程目录结构:


application .properties(配置信息)

spring.datasource.url=jdbc:mysql://39.100.23.188:3306/hr
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Dept.java

package com.newer.hr.pojo;

public class Dept {

	int id;
//	city
	String title;
	
	String loc;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getLoc() {
		return loc;
	}

	public void setLoc(String loc) {
		this.loc = loc;
	}

	@Override
	public String toString() {
		return "Dept [id=" + id + ", title=" + title + ", loc=" + loc + "]";
	}
	
}

Staff.java

package com.newer.hr.pojo;

import java.util.List;

/**
 * 实体类
 * @author Admin
 *
 */
public class Staff {


//	PK
	int id;
	
//	属性
	String name;
	
	String job;
	
	String phone;
	
//	@One 一个员工隶属一个部门
//	数据库列名: dept_id
	Dept dept;
	
	
//	一个人有多个地址
//	@Many
	List<Address> addressList;
	
	public List<Address> getAddressList() {
		return addressList;
	}
	
	public void setAddressList(List<Address> addressList) {
		this.addressList = addressList;
	}
	
	

	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 String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;
	}

	@Override
	public String toString() {
		return "Staff [id=" + id + ", name=" + name + ", job=" + job + ", phone=" + phone + ", dept=" + dept + "]";
	}
	
	
}

Address.java

package com.newer.hr.pojo;

public class Address {

	int id;
	
	String city;
	
	String street;
	
//	tel
	String phone;
	
	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}
	
	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}
	
	
	
}

DeptMapper.java(接口)

package com.newer.hr.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.newer.hr.pojo.Dept;

@Mapper
public interface DeptMapper {

	@Select("select * from dept")
	List<Dept>findAll();
	
	@Select("select * from dept where id=#{id}")
	@Results({
		@Result
	})
	Dept load(int id);
}

StaffMapper.java(接口)--重点

package com.newer.hr.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.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.type.JdbcType;

import com.newer.hr.pojo.Staff;
import com.newer.hr.pojo.Dept;

@Mapper
public interface StaffMapper {

	@Select("select * from staff")
	
//	匹配数据库表里字段名与类属性名
	@Results({

//		表里---》类
		@Result(column = "id",property = "id"),
		@Result(column = "name",property = "name"),
		@Result(column = "name",property = "phone"),
		@Result(column = "name",property = "job"),
//		属性的java类型,映射的类型(one),
		@Result(
				column = "dept_id",
				jdbcType = JdbcType.INTEGER,
				property = "dept",
				javaType = Dept.class,
//				一对一
//				select 执行一个映射方法,不是SQL语句
//				映射方法:1.SQL语句  2.表列名与类属性名之间的映射
				one=@One(select ="com.newer.hr.mapper.DeptMapper.load")
				)
	})
	
	List<Staff>findAll();
	
	@Select("select * from staff where id=#{id}")
//	匹配数据库表里字段名与类属性名
	@Results({
//		表里---》类
		@Result(column = "id",property = "id"),
		@Result(column = "name",property = "name"),
		@Result(column = "name",property = "phone"),
		@Result(column = "name",property = "job"),
		
		@Result(
//				staff表中的id
				column = "id",
//				类中的addressList属性是一个集合
				property = "addressList",
				javaType = List.class,
//				
				many=@Many(select="com.newer.hr.mapper.AddressMapper.findByStaffId")
				)
	})
	
	Staff load(int id);
}

AddressMapper.java(接口)

package com.newer.hr.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import com.newer.hr.pojo.Address;

@Mapper
public interface AddressMapper {

	/**
	 * 获得某个员工的地址
	 * @param id
	 * @return
	 */
	@Select("select * from address where staff_id=#{id}")
	@Results({
		@Result(column = "tel",property = "phone")
	})
	List<Address>findByStaffId(int id);
}

HomeController.java

package com.newer.hr.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.newer.hr.mapper.DeptMapper;
import com.newer.hr.mapper.StaffMapper;
import com.newer.hr.pojo.Dept;
import com.newer.hr.pojo.Staff;

@RestController
public class HomeController {

	@Autowired
	DeptMapper deptMapper;
	
	@Autowired
	StaffMapper staffMapper;
	
	@GetMapping("/dept")
	public List<Dept>a(){
		return deptMapper.findAll();
	}
	
	@GetMapping("/dept/{id}")
	public Dept b(@PathVariable int id) {
		return deptMapper.load(id);
	}
	
	
	@GetMapping("/staff")
	public List<Staff>c(){
		return staffMapper.findAll();
	}
	
	@GetMapping("/staff/{id}")
	public Staff d(@PathVariable int id) {
		return staffMapper.load(id);
	}
	
	
}

接下来运行程序,可以通过127.0.0.1:8080/名字访问数据库表中的数据了,还可以对表进行CRUD操作,甚至可以前后端分离开发,有兴趣的小伙伴可以去前面的博客看,


 关于MyBatis 中 @One 和 @Many 关联与映射以及阿里云的配置 就到这里了,欢迎有不懂的小伙伴留言!!!

正文到此结束
本文目录