Mybatis中association、collection、discriminator的使用


1、dbconfig.properties数据库连接配置

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://192.168.121.200:3306/mybatis
username=root
password=root

2、log4j.xml配置

<?xml version="1.0" encoding="UTF-8" ?>




    
        
        
            
        
    
    
        
    
    
        
    
    
        
        
    

3、mybatis-config.xml配置文件

<?xml version="1.0" encoding="UTF-8" ?>


    

    
        
        
        
    
    
    
        
    

    
        
            
            
                
                
                
                
            
        
    
    

        
    

4、实体类

public class User {
    private Long userId;
    private Long deptId;
    private String userName;
    private String email;
    private Dept dept;
}

public class Dept {
    private Long deptId;
    private String deptName;
    private List users;
}

5、Mapper接口

public interface UserMapper {
    public User getUserById(Long id);

    public User getUserAndDeptByUserId(Long userId);

    public User getUserAndDeptByUserIdStep(Long userId);

    public User getUserByDeptId(Long deptId);

}

public interface DeptMapper {
    public Dept getDeptByDeptId(Long deptId);

    public Dept getDeptAndUserByDeptId(Long deptId);

    public Dept getDeptAndUserByDeptIdStep(Long deptId);
}

6、mapper XML

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>




    
        
        
        
        
        
        
    

    
        
        
        
        
        
            
            
        
    

    




    
        
        
        
        
        
            
            
        
    

    



    
    


DeptMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>