栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis快速入门(二)(隔壁王大爷都学会了!)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis快速入门(二)(隔壁王大爷都学会了!)

一、ORM映射【重点】
1.1 MyBatis自动ORM失效

MyBatis只能自动维护库表”列名“与”属性名“相同时的一一对应关系,二者不同时,无法自动ORM。

自动ORM失效

1.2 方案一:列的别名

在SQL中使用 as 为查询字段添加列别名,以匹配属性名。


    
        SELECT mgr_id AS id , mgr_name AS username , mgr_pwd AS password
        FROM t_managers
        WHERe mgr_id = #{id} AND mgr_pwd = #{pwd}
    

1.3 方案二:结果映射(ResultMap - 查询结果的封装规则)

通过< resultMap id="" type="" >映射,匹配列名与属性名。


​
    
    
        
        
      
        
        
        
    
  
     
    
          SELECT p1.id,p1.name,p1.sex,p1.birthday,
          p2.id passport_id,p2.nationality,p2.expire
          FROM t_passenger p1 INNER JOIN t_passport p2
          ON p1.id = p2.passenger_id
          WHERe p1.id=#{id};
    


  • 
    
    
    
        
        
    
            
        
        
            
                
                
                    
                    
                    
                    
                
            
        
        
    
    
    
    
    
            
        
    

  • ">注意:指定“一方”关系时(对象),使用< association javaType="" >

6.测试
 @org.junit.Test
    public void find() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream resourceAsStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PassengerDao mapper = sqlSession.getMapper(PassengerDao.class);
        Passenger byId = mapper.findById(2);
        System.out.println(byId);
        sqlSession.close();
        resourceAsStream.close();
    }
运行结果:

 

2.2 oneToMany
1.创建表
CREATE TABLE t_department(
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAr(50),
    location VARCHAr(100)
)DEFAULT CHARSET =utf8;
​
INSERT INTO t_department VALUES(1,"教学部","北京"),(2,"研发部","上海");
​
CREATE TABLE t_employee(
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAr(50),
    salary DOUBLE,
    dept_id INT
)DEFAULT CHARSET =utf8;
​
INSERT INTO t_employee VALUES(1,"jack",1000.5,1);
INSERT INTO t_employee VALUES(2,"rose",2000.5,1);
INSERT INTO t_employee VALUES(3,"张三",3000.5,2);
INSERT INTO t_employee VALUES(4,"李四",4000.5,2);

2.创建实体类
package com.qianwz.entity;

import lombok.Data;

import java.util.List;

@Data
public class Department {
    private Integer id;
    private String name;
    private String location;

    List employees;
}
package com.qianwz.entity;

import lombok.Data;
@Data
public class Employee {
    private Integer id;
    private String name;
    private String salary;

    private List departments;
}
3.创建Dao
package com.qianwz.dao;

import com.qianwz.entity.Department;


public interface DepartmentDao {
    Department findById(Integer id);
}
package com.qianwz.dao;

import com.qianwz.entity.Employee;

public interface EmployeeDao {
    Employee findById(Integer id);
}
4.创建EmployeeDao.xml配置文件





    
    
        
        
        
        
            
            
            
        
    
    
          select d.id,d.name,location,e.id employeeId,e.name employeeName,salary
          from t_department d
          inner join t_employee e
          on d.id = e.dept_id
          where d.id = #{id}
    

  • ">注意:指定“多方”关系时(集合),使用< collection ofType="" >

6.测试
import com.qianwz.dao.DepartmentDao;
import com.qianwz.dao.EmployeeDao;
import com.qianwz.entity.Department;
import com.qianwz.entity.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class Test {
    @org.junit.Test
    public void test() throws IOException {
        String resourrce = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resourrce);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = build.openSession();
        DepartmentDao mapper = sqlSession.getMapper(DepartmentDao.class);
        Department byId = mapper.findById(1);
        System.out.println(byId);
        sqlSession.close();
        inputStream.close();
    }
    @org.junit.Test
    public void test2() throws IOException {
        String resourrce = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resourrce);
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = build.openSession();
        EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
        Employee dById = mapper.findById(1);
        System.out.println(dById);
        sqlSession.close();
        inputStream.close();
    }
}

 

 

2.3 ManyToMany
建立第三张关系表

 

1.创建表
CREATE TABLE t_student(
​
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAr(50),
    sex VARCHAr(1)
​
)DEFAULT CHARSET = utf8;
​
INSERT INTO t_student VALUES(1,'jack','m');
INSERT INTO t_student VALUES(2,'rose','f');
​
​
CREATE TABLE t_subject(
​
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAr(50),
    grade INT
​
)DEFAULT CHARSET = utf8;
​
INSERT INTO t_subject VALUES(1001,'JavaSE',1);
INSERT INTO t_subject VALUES(1002,'JavaEE',2);
​
CREATE TABLE t_stu_sub(
​
    student_id INT,
    subject_id INT
​
)DEFAULT CHARSET = utf8;
​
INSERT INTO t_stu_sub VALUES(1,1001);
INSERT INTO t_stu_sub VALUES(1,1002);
INSERT INTO t_stu_sub VALUES(2,1001);
INSERT INTO t_stu_sub VALUES(2,1002);

2.创建实体类
package com.qwz.entity;

import lombok.Data;

import java.util.List;
@Data
public class Student {
    private Integer id;
    private String name;
    private String sex;

    private List subjects;
}
package com.qwz.entity;

import lombok.Data;

import java.util.List;

@Data
public class Subject {
    private Integer id;
    private String name;
    private Integer grade;

    private List students;
}
3.创建Dao
package com.qwz.dao;

import com.qwz.entity.Student;

import java.util.List;

public interface StudentDao {
    List findStudentSubject();
}
package com.qwz.dao;

import com.qwz.entity.Subject;

import java.util.List;

public interface SubjectDao {
    List findSubjectStudent();
}
4.创建StudentDao.xml





    
    
        
        
        
        
        
            
            
            
        
    
    
    

5.创建mybatis-config.xml



    
    
    
    
        
        
    
    
        
            
            
                
                
                
                
            
        
    
    
        
        
        
        
        
        
    
  • ">注意:指定“多方”关系时(集合),使用< collection ofType="" >

6.测试
import com.qwz.dao.StudentDao;
import com.qwz.entity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test {
    @org.junit.Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream  inputStream= Resources.getResourceAsStream(resource);
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = build.openSession();
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        List studentSubject = mapper.findStudentSubject();
        for (Student student : studentSubject) {
            System.out.println(student);
        }
        sqlSession.close();
        inputStream.close();
    }
}

 

2.4 关系总结

一方,添加集合;多方,添加对象。

双方均可建立关系属性,建立关系属性后,对应的Mapper文件中需使用< ResultMap >完成多表映射。

持有对象关系属性,使用< association property="***" javaType="***" >

持有集合关系属性,使用< collection property="***" ofType="***" >

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/309455.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号